PYTHON 文件系统
在 Python 中,文件系统操作通常通过内置的 os 模块和 os.path 模块来进行。这些模块提供了许多函数和方法,可以让你操作文件和目录,例如创建、删除、移动、复制文件,以及查询文件属性等。
主要模块和函数
os 模块
os 模块提供了访问操作系统功能的方法,包括文件系统操作。
import os # 获取当前工作目录 current_dir = os.getcwd() print("Current directory:", current_dir) # 列出目录下的文件和子目录 files_and_dirs = os.listdir(current_dir) print("Files and directories:", files_and_dirs) # 创建目录 new_dir = os.path.join(current_dir, 'new_directory') os.mkdir(new_dir) # 删除目录 os.rmdir(new_dir) # 检查文件或目录是否存在 if os.path.exists(new_dir): print(f"{new_dir} exists.") else: print(f"{new_dir} does not exist.")
os.path 模块
os.path 模块提供了路径操作相关的函数,可以处理文件名和目录名的操作,还可以查询文件属性。
import os.path # 检查路径是否是文件 file_path = os.path.join(current_dir, 'example.txt') if os.path.isfile(file_path): print(f"{file_path} is a file.") # 检查路径是否是目录 if os.path.isdir(current_dir): print(f"{current_dir} is a directory.") # 获取文件的大小 file_size = os.path.getsize(file_path) print(f"Size of {file_path}: {file_size} bytes.") # 获取文件的最后访问时间 access_time = os.path.getatime(file_path) print(f"Last accessed time of {file_path}: {access_time}.")
shutil 模块
shutil 模块提供了高级的文件操作函数,例如复制文件、删除目录等,对于文件系统操作更加方便。
import shutil # 复制文件 src_file = os.path.join(current_dir, 'source.txt') dest_file = os.path.join(current_dir, 'destination.txt') shutil.copy(src_file, dest_file) # 删除文件 os.remove(dest_file) # 复制整个目录树 src_dir = os.path.join(current_dir, 'source_directory') dest_dir = os.path.join(current_dir, 'destination_directory') shutil.copytree(src_dir, dest_dir) # 删除整个目录树 shutil.rmtree(dest_dir)
注意事项
在进行文件系统操作时,务必谨慎处理,特别是对于删除操作,确保文件和目录的存在和权限。
使用 os.path.join() 来构建路径可以增强代码的可移植性,因为它会根据操作系统的规范来构建路径。
Python 的文件系统操作模块提供了丰富的功能和灵活的方法,使得处理文件和目录变得相对简单和直观。通过这些模块,你可以方便地管理文件、查询文件属性、复制和删除文件等。