下面将详细介绍如何使用 pathlib 模块来处理文件路径。我们将从创建 Path 对象、绝对路径与相对路径、访问文件路径分量,以及检查文件路径是否存在等几个方面进行讲解。
要使用 pathlib,首先需要导入模块并创建一个 Path 对象。
1 2 3 4 5 6 7 8 9 |
from pathlib import Path
# 创建表示当前工作目录的Path对象 current_directory = Path.cwd() print(f"当前工作目录: {current_directory}")
# 创建表示特定文件的Path对象 file_path = Path("example.txt") print(f"指定文件路径: {file_path}") |
1 2 3 4 5 6 7 |
# 获取绝对路径 absolute_path = file_path.resolve() print(f"绝对路径: {absolute_path}")
# 使用相对路径创建Path对象 relative_path = Path("subfolder/example.txt") print(f"相对路径: {relative_path}") |
Path 对象提供了一些属性和方法,用于访问文件路径的不同部分。
1 2 3 4 5 6 |
# 分析文件路径 print(f"文件名: {file_path.name}") # 文件名 print(f"文件后缀: {file_path.suffix}") # 文件扩展名 print(f"文件名(不带扩展): {file_path.stem}") # 不带扩展的文件名 print(f"父级目录: {file_path.parent}") # 父目录 print(f"根目录: {file_path.anchor}") # 根目录(在Windows上为驱动器字母) |
可以使用 exists() 方法来检查文件或目录是否存在,此外,还有其他有用的方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# 检查文件是否存在 if file_path.exists(): print(f"{file_path} 文件存在") else: print(f"{file_path} 文件不存在")
# 检查是否是文件 if file_path.is_file(): print(f"{file_path} 是一个文件") elif file_path.is_dir(): print(f"{file_path} 是一个目录") else: print(f"{file_path} 既不是文件也不是目录") |
pathlib 还提供了许多其他有用的方法,如遍历目录、读取文件内容等。
1 2 3 |
# 列出当前目录下的所有文件和子目录 for item in current_directory.iterdir(): print(item) |
1 2 3 4 5 |
# 读取文件内容(确保文件存在) if file_path.exists() and file_path.is_file(): with file_path.open('r') as f: content = f.read() print(content) |
使用 pathlib 可以使得文件路径操作变得更加简洁明了,非常适合现代Python编程。