Pythonpathlib模块介绍
- 游戏开发
- 2025-08-25 22:12:02

Python 的 pathlib 模块是标准库中的一种现代化、面向对象的路径处理工具。与传统的 os.path 模块相比,pathlib 提供了更简洁、直观的 API 来处理文件路径、目录操作和文件 I/O。
以下是 pathlib 的详细介绍、常见用法和实用示例。
1. pathlib 基本概念
pathlib 引入了 Path 类,表示文件或目录路径,支持跨平台操作(Windows、macOS、Linux)。
from pathlib import Path # 创建 Path 对象 p = Path("example_folder/example_file.txt") print(p) # example_folder/example_file.txt print(p.name) # example_file.txt print(p.stem) # example_file print(p.suffix) # .txt print(p.parent) # example_folder print(p.exists()) # False(文件不存在) 2. 创建路径 2.1. 当前工作目录 from pathlib import Path # 获取当前工作目录 cwd = Path.cwd() print(f"当前工作目录: {cwd}") 2.2. 家目录和根目录 print(Path.home()) # 用户家目录 print(Path("/")) # 根目录 2.3. 拼接路径使用 / 作为路径拼接运算符,更加简洁。
p = Path("example_folder") / "example_file.txt" print(p) # example_folder/example_file.txt等效于传统的 os.path.join():
import os print(os.path.join("example_folder", "example_file.txt")) 3. 文件和目录操作 3.1. 创建目录 # 创建单级目录 Path("new_folder").mkdir(exist_ok=True) # 创建多级目录 Path("parent_folder/child_folder").mkdir(parents=True, exist_ok=True) 3.2. 创建文件 # 创建文件 file_path = Path("example_folder/example_file.txt") file_path.parent.mkdir(parents=True, exist_ok=True) # 确保目录存在 file_path.touch(exist_ok=True) print(file_path.exists()) # True 3.3. 删除文件和目录 # 删除文件 file_path.unlink(missing_ok=True) # 删除空目录 Path("example_folder").rmdir() # 递归删除目录 import shutil shutil.rmtree("parent_folder", ignore_errors=True) 4. 路径属性和检查 p = Path("example_folder/example_file.txt") print(p.exists()) # 文件/目录是否存在 print(p.is_file()) # 是否是文件 print(p.is_dir()) # 是否是目录 print(p.is_absolute()) # 是否是绝对路径 print(p.stat().st_size) # 文件大小(字节) 5. 遍历目录 5.1. 遍历当前目录下的所有文件 for path in Path(".").iterdir(): print(path) 5.2. 递归遍历所有文件 # 找到所有 .txt 文件 for path in Path(".").rglob("*.txt"): print(path)等效于 os.walk():
import os for root, _, files in os.walk("."): for file in files: if file.endswith(".txt"): print(os.path.join(root, file)) 6. 读写文件 6.1. 读取文件 file_path = Path("example_folder/example_file.txt") # 写入示例文本 file_path.write_text("Hello, Pathlib!", encoding="utf-8") # 读取文件内容 content = file_path.read_text(encoding="utf-8") print(content) 6.2. 逐行读取 with file_path.open("r", encoding="utf-8") as f: for line in f: print(line.strip()) 6.3. 写入文件 # 写入(覆盖) file_path.write_text("New content!", encoding="utf-8") # 追加写入 with file_path.open("a", encoding="utf-8") as f: f.write("\nAppend this line.") 7. 路径操作示例 7.1. 获取文件名和后缀 p = Path("example_folder/example_file.txt") print(p.name) # example_file.txt print(p.stem) # example_file print(p.suffix) # .txt print(p.parent) # example_folder 7.2. 规范化路径 p = Path("folder//subfolder/../file.txt") print(p.resolve()) # 规范化路径 7.3. 复制、移动和重命名 import shutil # 复制文件 shutil.copy("example_folder/example_file.txt", "backup.txt") # 移动文件 shutil.move("backup.txt", "example_folder/moved_file.txt") # 重命名文件 Path("example_folder/moved_file.txt").rename("example_folder/renamed_file.txt") 8. pathlib vs os.path 对比 功能pathlib 示例os.path 示例获取当前目录Path.cwd()os.getcwd()拼接路径Path("folder") / "file"os.path.join("folder", "file")判断存在Path("file.txt").exists()os.path.exists("file.txt")读取文件path.read_text()open("file.txt").read()遍历文件夹Path(".").rglob("*.txt")os.walk(".") + fnmatch创建目录Path("folder").mkdir()os.makedirs("folder", exist_ok=True)9. pathlib 的优势 面向对象:路径是一个对象,不是字符串。跨平台:自动适配 Windows 和 Unix 风格路径。简洁易读:使用 / 拼接路径,比 os.path.join 更直观。内置文件 I/O:直接读写文件,无需 open()。强大的模式匹配:Path.glob() 和 Path.rglob() 高效递归查找。
10. 适用场景总结 场景推荐方式简单路径拼接pathlib.Path复杂路径操作pathlib.Path仅检查文件存在pathlib.Path.exists()读取小文件pathlib.Path.read_text()处理大文件open() 配合 pathlib.Path
Pythonpathlib模块介绍由讯客互联游戏开发栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“Pythonpathlib模块介绍”
上一篇
自动驾驶之BEV概述