Python中如何使用pathlib模块进行路径操作?
Path('/home/stephen/shenjianlin') PosixPath('/home/stephen/shenjianlin') Path('/home/stephen/shenjianlin').parent PosixPath('/home/stephen') 这里我要的是路径 怎么有 PosixPath 这种东西出来?难道要正则处理?
Python中如何使用pathlib模块进行路径操作?
6 回复
str(Path())
Path().stem
Path().name
用 pathlib 操作路径比老的 os.path 爽多了,面向对象的方式更直观。直接上代码例子:
from pathlib import Path
# 创建Path对象
p = Path('/home/user/docs/file.txt')
# 获取路径各部分
print(p.name) # 'file.txt'
print(p.stem) # 'file'
print(p.suffix) # '.txt'
print(p.parent) # '/home/user/docs'
# 路径拼接(推荐用/操作符)
new_path = p.parent / 'new_file.txt'
# 检查路径
print(p.exists()) # 是否存在
print(p.is_file()) # 是否是文件
print(p.is_dir()) # 是否是目录
# 创建目录(自动创建父目录)
Path('/tmp/new_folder').mkdir(parents=True, exist_ok=True)
# 遍历目录
for file in Path('.').glob('*.py'): # 当前目录所有.py文件
print(file)
# 读写文件
content = p.read_text() # 读取文本
p.write_text('hello') # 写入文本
# 解析路径
print(p.absolute()) # 绝对路径
print(p.resolve()) # 解析符号链接
关键点:Path对象直接代表路径,用/拼接路径,方法链式调用很流畅。比字符串操作安全,跨平台兼容性好。
一句话建议:新项目直接用pathlib替代os.path。
因为你在 posix 兼容的系统啊, Path 类是一个接口, posixpath 类是具体实现, 你用就行了
读一读 官方的帮助文档
写得很清楚的
解决了谢谢
你说的官方文档是那个 piyi 的 homepage 吗?

