当前位置: 首页 > news >正文

Python pathlib模块介绍

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 的优势

  1. 面向对象:路径是一个对象,不是字符串。
  2. 跨平台:自动适配 Windows 和 Unix 风格路径。
  3. 简洁易读:使用 / 拼接路径,比 os.path.join 更直观。
  4. 内置文件 I/O:直接读写文件,无需 open()
  5. 强大的模式匹配Path.glob() 和 Path.rglob() 高效递归查找。

10. 适用场景总结

场景推荐方式
简单路径拼接pathlib.Path
复杂路径操作pathlib.Path
仅检查文件存在pathlib.Path.exists()
读取小文件pathlib.Path.read_text()
处理大文件open() 配合 pathlib.Path

相关文章:

  • 【面试】Redis 常见面试题
  • 专利申请流程详解:从创意到授权的完整指南
  • Nginx 负载均衡详解
  • 在UBUNTU下搭建Deepseek
  • 力扣hot100——螺旋矩阵 超简单易懂的模拟搜索方法
  • 专题--Redis
  • STM32 HAL库标准库+ESP8266+机智云
  • 树莓派4基于Debian GNU/Linux 12 (Bookworm)添加多个静态ipv4网络
  • 【找工作】C++和算法复习(自用)
  • MySQL(2)索引篇
  • 金融数据库数字化转型:性能优化的实战经验
  • 【自动化脚本工具】Hammerspoon (Mac)
  • OpenCV对比度增强
  • 【Python】Python入门——笔记合集
  • 5.5 Soft Prompt技术:任务特定微调的新范式
  • 循环神经网络RNN原理与优化
  • Interactive High-Quality Green-Screen Keying via Color Unmixing
  • vue 父组件和子组件中v-model和props的使用和区别
  • 形参和实参
  • 强化学习入门
  • 解放日报:上海深化改革开放,系统集成创新局
  • 以“最美通缉犯”为噱头直播?光明网:违法犯罪不应成网红跳板
  • 书业观察|一本书的颜值革命:从毛边皮面到爆火的刷边书
  • 国家统计局:一季度全国规模以上文化及相关产业企业营业收入增长6.2%
  • 深圳一季度GDP为8950.49亿元,同比增长5.2%
  • 当AI开始深度思考,人类如何守住自己的慢思考能力?