欢迎访问宙启技术站
智能推送

使用Python的Posix模块实现文件系统操作

发布时间:2024-01-16 00:50:07

Python的Posix模块(也称为os模块)提供了一系列函数来进行文件系统操作。这些函数可以用于创建、删除、复制、移动文件和目录,以及获取文件属性和目录内容等。

下面是一些常用的Posix模块函数及其使用示例:

1. 获取当前工作目录(getcwd()函数):

import os

current_dir = os.getcwd()
print(current_dir)

输出:

/Users/username/Documents

2. 创建目录(mkdir()函数):

import os

new_dir = os.path.join(os.getcwd(), 'new_directory')
os.mkdir(new_dir)

3. 创建多级目录(makedirs()函数):

import os

new_dir = os.path.join(os.getcwd(), 'new_directory1', 'new_directory2')
os.makedirs(new_dir)

4. 获取目录下的文件和子目录列表(listdir()函数):

import os

files = os.listdir(os.getcwd())
print(files)

输出:

['file1.txt', 'folder1', 'file2.txt']

5. 删除文件(remove()函数):

import os

file_path = os.path.join(os.getcwd(), 'file.txt')
os.remove(file_path)

6. 删除目录(rmdir()函数):

import os

dir_path = os.path.join(os.getcwd(), 'directory')
os.rmdir(dir_path)

7. 删除多级目录(removedirs()函数):

import os

dir_path = os.path.join(os.getcwd(), 'directory1', 'directory2')
os.removedirs(dir_path)

8. 重命名文件或目录(rename()函数):

import os

old_name = os.path.join(os.getcwd(), 'file1.txt')
new_name = os.path.join(os.getcwd(), 'file2.txt')
os.rename(old_name, new_name)

9. 复制文件(copy()函数):

import shutil

src_file = os.path.join(os.getcwd(), 'file.txt')
dst_file = os.path.join(os.getcwd(), 'file_copy.txt')
shutil.copy(src_file, dst_file)

10. 移动文件(move()函数):

import shutil

src_file = os.path.join(os.getcwd(), 'file.txt')
dst_dir = os.path.join(os.getcwd(), 'new_directory')
shutil.move(src_file, dst_dir)

11. 获取文件属性(stat()函数):

import os

file_path = os.path.join(os.getcwd(), 'file.txt')
file_stat = os.stat(file_path)
print(file_stat)

输出:

os.stat_result(
    st_mode=33188, st_ino=65465465, st_dev=16777220, 
    st_nlink=1, st_uid=501, st_gid=20, st_size=42, 
    st_atime=1637908224, st_mtime=1637908224, st_ctime=1637908163
)

以上是一些基本的文件系统操作函数和使用示例。通过Posix模块,我们可以轻松地进行文件和目录的创建、删除、复制、移动等操作,同时也可以获取文件的属性信息。