Using pathlib module in python3

Using pathlib module in Python3

在 Python 中,pathlib 模块(从 Python 3.4 开始引入)是对传统 os.path 模块的面向对象封装,它提供了更简洁、直观和现代的方式来处理文件路径和目录操作。相比 os.pathpathlib 不仅语法更优雅,而且在某些场景下也具有更高的效率和更好的可读性。

官网文档: pathlib

✅ 一、pathlib 的高效方法总结

以下是一些 pathlib.Path 类中常用且效率较高的方法:

方法/属性 功能说明 效率优势
Path.exists() 判断路径是否存在 更直观,替代 os.path.exists()
Path.is_file() 判断是否是文件 替代 os.path.isfile(),无需拼接路径字符串
Path.is_dir() 判断是否是目录 替代 os.path.isdir()
Path.glob(pattern) / Path.rglob(pattern) 查找匹配的文件(递归) 替代 glob.glob()os.walk(),更灵活
Path.iterdir() 遍历目录下的所有文件和子目录 替代 os.listdir(),返回 Path 对象,便于链式调用
Path.read_text(encoding=...) 读取文本文件内容 封装了 open/read/close,简单安全
Path.write_text(data, encoding=...) 写入文本文件 同上,自动管理资源
Path.mkdir(parents=True, exist_ok=True) 创建多层目录 替代 os.makedirs(..., exist_ok=True),更简洁
Path.resolve() 返回绝对路径并解析符号链接 替代 os.path.abspath() + os.path.realpath()
Path.with_suffix() / Path.with_name() 修改文件名或后缀 非常方便,避免手动字符串拼接

✅ 二、与 os.path 的对比

功能 os.path 方式 pathlib 方式 优势说明
拼接路径 os.path.join('a', 'b') Path('a') / 'b' 使用 / 运算符更直观
获取父目录 os.path.dirname(path) Path(path).parent 属性访问更简洁
文件扩展名 os.path.splitext(path)[1] Path(path).suffix 更语义化
路径是否存在 os.path.exists(path) Path(path).exists() 更 OOP,代码结构清晰
遍历目录 os.listdir(path) Path(path).iterdir() 返回 Path 对象,易于进一步操作
递归查找 os.walk() Path.glob('**/*')rglob() 更简洁易读
读写文件 open(path, 'r').read() Path.read_text() / write_text() 更简洁安全,自动关闭文件

✅ 三、为什么 pathlib 效率更高?

  1. 面向对象设计:路径作为对象来处理,可以链式调用多个方法。
  2. 减少字符串操作:避免手动拼接路径,提高安全性与可维护性。
  3. 内置方法丰富:许多功能无需额外导入模块(如 glob, os 等)。
  4. 跨平台兼容性强:自动适配 Windows、Linux、macOS 的路径格式。
  5. 性能不输 os.path:底层实现基于 os,但逻辑更清晰,实际性能相当甚至更优(尤其在大量文件操作时)。

✅ 四、示例对比

示例 1:遍历一个目录中的 .txt 文件

  • os.path 版本:

    1
    2
    3
    4
    5
    6
    import os

    for filename in os.listdir('mydir'):
    path = os.path.join('mydir', filename)
    if os.path.isfile(path) and path.endswith('.txt'):
    print(path)
  • pathlib 版本:

    1
    2
    3
    4
    5
    from pathlib import Path

    for file in Path('mydir').iterdir():
    if file.is_file() and file.suffix == '.txt':
    print(file)

示例 2:递归查找所有 .py 文件

  • os.path + os.walk()

    1
    2
    3
    4
    5
    6
    import os

    for root, dirs, files in os.walk('.'):
    for file in files:
    if file.endswith('.py'):
    print(os.path.join(root, file))
  • pathlib

    1
    2
    3
    4
    from pathlib import Path

    for file in Path('.').rglob('*.py'):
    print(file)

✅ 五、建议使用场景

场景 推荐方式
新项目开发 🟢 pathlib(推荐)
维护旧代码 🔵 可继续使用 os.path,逐步迁移到 pathlib
高频路径操作 🟢 pathlib 更清晰、不易出错
简单脚本 🔵 根据习惯选择,两者皆可

✅ 六、总结

对比维度 os.path pathlib
风格 函数式 面向对象
可读性 一般
易用性 较低
性能 相当 相当
推荐程度 ❌ 已逐渐淘汰 ✅ 官方推荐新代码使用

如果你正在写新的 Python 代码,强烈建议使用 pathlib,它不仅更现代、更易维护,而且很多库也开始原生支持 Path 对象(如 shutil, json, pandas 等),未来趋势明显。

坚持原创技术分享,您的支持将鼓励我继续创作!
0%