Python pathlib 模块

一、pathlib 模块概述

pathlib 模块是 Python 3.4 及以上版本引入的标准库,它基于面向对象的思想,将文件系统路径抽象为对象,通过对象的属性和方法来完成路径的各种操作,相比于 os 模块可以写出更简洁,易读的代码。pathlib 模块支持不同操作系统的路径格式,自动处理路径分隔符的差异,使得代码在不同平台上具有更好的兼容性。

二、Path 类

Path 类是 pathlib 模块中最常用的类,它是所有具体路径类的基类。根据不同的操作系统,会自动选择合适的子类(如 PosixPath 用于 Unix 系统,WindowsPath 用于 Windows 系统)。

1. 创建 Path 对象

可以使用不同的方式创建 Path 对象:
from pathlib import Path

# 相对路径
relative_path = Path('data')
print(relative_path)

# 绝对路径
absolute_path = Path('/home/user/data')
print(absolute_path)

# 组合路径
combined_path = Path('home') / 'user' / 'data'
print(combined_path)
这里使用 / 运算符来组合路径,它会自动处理路径分隔符,使代码更简洁。

2.Path 对象的属性

属性名 描述 示例
name 返回路径的最后一部分,即文件名或目录名 path = Path('/home/user/data/file.txt'); print(path.name) 输出 file.txt
stem 返回文件名(不包含扩展名) path = Path('/home/user/data/file.txt'); print(path.stem) 输出 file
suffix 返回文件的扩展名 path = Path('/home/user/data/file.txt'); print(path.suffix) 输出 .txt
parent 返回路径的父目录 path = Path('/home/user/data/file.txt'); print(path.parent) 输出 /home/user/data
parents 返回一个可迭代对象,包含所有上级目录 path = Path('/home/user/data/file.txt'); for p in path.parents: print(p) 依次输出 /home/user/data、/home/user、/home、/

3.Path 对象的方法

(1)路径判断方法
方法名 描述 示例
exists() 判断路径是否存在 path = Path('/home/user/data/file.txt'); print(path.exists())
is_dir() 判断路径是否为目录 path = Path('/home/user/data'); print(path.is_dir())
is_file() 判断路径是否为文件 path = Path('/home/user/data/file.txt'); print(path.is_file())

(2)文件和目录操作方法
方法名 描述 示例
mkdir(mode=0o777, parents=False, exist_ok=False) 创建目录。parents 为 True 时会创建所有必要的上级目录;exist_ok 为 True 时,如果目录已存在不会抛出异常 path = Path('new_dir'); path.mkdir(parents=True, exist_ok=True)
rmdir() 删除空目录  path = Path('empty_dir'); path.rmdir()
unlink(missing_ok=False)  删除文件。missing_ok 为 True 时,如果文件不存在不会抛出异常 path = Path('temp_file.txt'); path.unlink(missing_ok=True)
rename(target) 重命名文件或目录 old_path = Path('old_name.txt'); new_path = Path('new_name.txt'); old_path.rename(new_path)
(3) 文件内容读写方法
方法名 描述 示例
read_text(encoding=None) 以文本模式读取文件内容 path = Path('file.txt'); content = path.read_text(); print(content)
write_text(data, encoding=None) 以文本模式写入文件内容  path = Path('file.txt'); path.write_text('Hello, World!')
read_bytes()  以二进制模式读取文件内容 path = Path('image.jpg'); data = path.read_bytes()
write_bytes(data) 以二进制模式写入文件内容  path = Path('new_image.jpg'); path.write_bytes(data)

三、PurePath 类

PurePath 类用于处理纯粹的路径,不涉及实际的文件系统操作。它有两个子类:PurePosixPath 和 PureWindowsPath,分别用于处理 Unix 和 Windows 风格的路径。

1. 创建 PurePath 对象

from pathlib import PurePath, PurePosixPath, PureWindowsPath

# 创建 PurePath 对象
pure_path = PurePath('home', 'user', 'data')
print(pure_path)

# 创建 PurePosixPath 对象
posix_path = PurePosixPath('/home/user/data')
print(posix_path)

# 创建 PureWindowsPath 对象
windows_path = PureWindowsPath('C:\\Users\\user\\data')
print(windows_path)

2.PurePath 对象的主要用途

PurePath 对象主要用于路径的解析和操作,比如路径的拼接、拆分、判断等,不进行实际的文件系统访问。例如:
pure_path = PurePath('home', 'user', 'data')
print(pure_path.joinpath('file.txt')) # 拼接路径
print(pure_path.parts) # 拆分路径为元组

三、路径遍历

1.iterdir() 方法

iterdir() 方法用于迭代目录中的所有项,返回一个迭代器,包含目录下的所有文件和子目录。
path = Path('data')
for item in path.iterdir():
  print(item)

2.glob(pattern) 方法

glob(pattern) 方法用于根据通配符模式匹配目录中的文件和子目录。
path = Path('data')
# 匹配所有 .txt 文件
for txt_file in path.glob('*.txt'):
  print(txt_file)
path = Path('data')

# 匹配所有 .txt 文件
for txt_file in path.glob('*.txt'):
print(txt_file)

# 递归匹配所有 .txt 文件
for txt_file in path.glob('**/*.txt'):
print(txt_file)

3.rglob(pattern) 方法

rglob(pattern) 方法是 glob('**/pattern') 的快捷方式,用于递归匹配目录及其子目录下的所有符合模式的文件和子目录。
path = Path('data')
for txt_file in path.rglob('*.txt'):
  print(txt_file)

四、实际应用场景

1.批量文件处理

可以使用 pathlib 模块遍历目录,对其中的文件进行批量处理,比如重命名、复制、删除等操作。
from pathlib import Path

# 遍历 data 目录下的所有 .txt 文件
data_dir = Path('data')
for txt_file in data_dir.glob('*.txt'):
  new_name = txt_file.stem + '_new' + txt_file.suffix
  new_path = txt_file.with_name(new_name)
  txt_file.rename(new_path)

2.配置文件读取

使用 pathlib 模块可以方便地定位和读取配置文件。
from pathlib import Path

config_path = Path('config.ini')
if config_path.exists():
  config_content = config_path.read_text()
  print(config_content)

3.获取目录

知识点:
Path.cwd(),返回文件当前所在目录。
Path.home(),返回用户的主目录。

from pathlib import Path
currentPath = Path.cwd()
homePath = Path.home()
print("文件当前所在目录:%s\n用户主目录:%s" %(currentPath, homePath))

4.目录拼接

知识点:斜杠 / 操作符用于拼接路径,比如创建子路径。

应用示例:
from pathlib import Path
currentPath = Path.cwd()
newPath = currentPath / 'python-100'
print("新目录为:%s" %(newPath))

5.创建、删除目录

知识点:
Path.mkdir(),创建给定路径的目录。
Path.rmdir(),删除该目录,目录文件夹必须为空。

应用示例:
from pathlib import Path
currentPath = Path.cwd()
makePath = currentPath / 'python-100'
makePath.mkdir()
print("创建的目录为:%s" %(nmakePath))

from pathlib import Path
currentPath = Path.cwd()
delPath = currentPath / 'python-100'
delPath.rmdir()
print("删除的目录为:%s" %(delPath))

6.读写文件

知识点:
Path.open(mode='r'),以 "r" 格式打开 Path 路径下的文件,若文件不存在即创建后打开。 Path.read_bytes(),打开 Path 路径下的文件,以字节流格式读取文件内容,等同 open 操作文件的 "rb" 格式。 Path.read_text(),打开 Path 路径下的文件,以 str 格式读取文件内容,等同 open 操作文件的 "r" 格式。 Path.write_bytes(),对 Path 路径下的文件进行写操作,等同 open 操作文件的 "wb" 格式。 Path.write_text(),对 Path 路径下的文件进行写操作,等同 open 操作文件的 "w" 格式。
应用示例:
from pathlib import Path currentPath = Path.cwd() mkPath = currentPath / 'python-100.txt' with mkPath.open('w') as f: # 创建并以 "w" 格式打开 python-100.txt 文件。 f.write('python-100') # 写入 python-100 字符串。 f = open(mkPath, 'r') print("读取的文件内容为:%s" % f.read()) f.close() from pathlib import Path currentPath = Path.cwd() mkPathText = currentPath / 'python-100-text.txt' mkPathText.write_text('python-100') print("读取的文件内容为:%s" % mkPathText.read_text()) str2byte = bytes('python-100', encoding = 'utf-8') mkPathByte = currentPath / 'python-100-byte.txt' mkPathByte.write_bytes(str2byte) print("读取的文件内容为:%s" % mkPathByte.read_bytes())

7.获取文件所在目录的不同部分字段

知识点:
Path.resolve(),通过传入文件名,返回文件的完整路径。 Path.name,可以获取文件的名字,包含后缀名。 Path.parent,返回文件所在文件夹的名字。 Path.stem,获取文件名不包含后缀名。 Path.suffix,获取文件的后缀名。 Path.anchor,获取文件所在的盘符。

应用示例:
from pathlib import Path txtPath = Path('python-100.txt') nowPath = txtPath.resolve() print("文件的完整路径为:%s" % nowPath) print("文件完整名称为(文件名+后缀名):%s" % nowPath.name) print("文件名为:%s" % nowPath.stem) print("文件后缀名为:%s" % nowPath.suffix) print("文件所在的文件夹名为:%s" % nowPath.parent) print("文件所在的盘符为:%s" % nowPath.anchor)
8.文件、路径是否存在判断
知识点:
Path.exists(),判断 Path 路径是否指向一个已存在的文件或目录,返回 True 或 False。 Path.is_dir(),判断 Path 是否是一个路径,返回 True 或 False。 Path.is_file(),判断 Path 是否指向一个文件,返回 True 或 False。
应用示例:
from pathlib import Path currentPath = Path.cwd() / 'python' print(currentPath.exists()) # 判断是否存在 python 文件夹,此时返回 False。 print(currentPath.is_dir()) # 判断是否存在 python 文件夹,此时返回 False。 currentPath.mkdir() # 创建 python 文件夹。 print(currentPath.exists()) # 判断是否存在 python 文件夹,此时返回 True。 print(currentPath.is_dir()) # 判断是否存在 python 文件夹,此时返回 True。 currentPath = Path.cwd() / 'python-100.txt' print(currentPath.exists()) # 判断是否存在 python-100.txt 文件,此时文件未创建返回 False。 print(currentPath.is_file()) # 判断是否存在 python-100.txt 文件,此时文件未创建返回 False。 f = open(currentPath,'w') # 创建 python-100.txt 文件。 f.close() print(currentPath.exists()) # 判断是否存在 python-100.txt 文件,此时返回 True。 print(currentPath.is_file()) # 判断是否存在 python-100.txt 文件,此时返回 True。

9.文件统计以及匹配查找知识点:

Path.iterdir(),返回 Path 目录文件夹下的所有文件,返回的是一个生成器类型。
Path.glob(pattern),返回 Path 目录文件夹下所有与 pattern 匹配的文件,返回的是一个生成器类型。
Path.rglob(pattern),返回 Path 路径下所有子文件夹中与 pattern 匹配的文件,返回的是一个生成器类型。
# 使用 Path.iterdir() 获取当前文件下的所有文件,并根据后缀名统计其个数。

应用示例:
import pathlib from collections import Counter currentPath = pathlib.Path.cwd() gen = (i.suffix for i in currentPath.iterdir()) print(Counter(gen)) import pathlib from collections import Counter currentPath = pathlib.Path.cwd() gen = (i.suffix for i in currentPath.glob('*.txt')) # 获取当前文件下的所有 txt 文件,并统计其个数。 print(Counter(gen)) gen = (i.suffix for i in currentPath.rglob('*.txt')) # 获取目录中子文件夹下的所有 txt 文件,并统计其个数。 print(Counter(gen))
posted @ 2025-08-22 10:12  百衲本  阅读(200)  评论(0)    收藏  举报
cnblogs_post_body { color: black; font: 0.875em/1.5em "微软雅黑" , "PTSans" , "Arial" ,sans-serif; font-size: 15px; } cnblogs_post_body h1 { text-align:center; background: #333366; border-radius: 6px 6px 6px 6px; box-shadow: 0 0 0 1px #5F5A4B, 1px 1px 6px 1px rgba(10, 10, 0, 0.5); color: #FFFFFF; font-family: "微软雅黑" , "宋体" , "黑体" ,Arial; font-size: 23px; font-weight: bold; height: 25px; line-height: 25px; margin: 18px 0 !important; padding: 8px 0 5px 5px; text-shadow: 2px 2px 3px #222222; } cnblogs_post_body h2 { text-align:center; background: #006699; border-radius: 6px 6px 6px 6px; box-shadow: 0 0 0 1px #5F5A4B, 1px 1px 6px 1px rgba(10, 10, 0, 0.5); color: #FFFFFF; font-family: "微软雅黑" , "宋体" , "黑体" ,Arial; font-size: 20px; font-weight: bold; height: 25px; line-height: 25px; margin: 18px 0 !important; padding: 8px 0 5px 5px; text-shadow: 2px 2px 3px #222222; } cnblogs_post_body h3 { background: #2B6695; border-radius: 6px 6px 6px 6px; box-shadow: 0 0 0 1px #5F5A4B, 1px 1px 6px 1px rgba(10, 10, 0, 0.5); color: #FFFFFF; font-family: "微软雅黑" , "宋体" , "黑体" ,Arial; font-size: 18px; font-weight: bold; height: 25px; line-height: 25px; margin: 18px 0 !important; padding: 8px 0 5px 5px; text-shadow: 2px 2px 3px #222222; } 回到顶部 博客侧边栏 回到顶部 页首代码 回到顶部 页脚代码