1、常规写法os.path
假设我们需要获取某个文件夹下所有的txt文件
import os
dir_path = "/home/user/documents"# Find all text files inside a directory
files = [os.path.join(dir_path, f) for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f)) and f.endswith(".txt")]
使用pathlib写法:
from pathlib import Path
dir_path = Path("/home/user/documents")
files = list(dir_path.glob("*.txt"))
简单高效。
os.path将系统路径视为字符串,容易出现混乱。而pathlib将路径表示为独特的对象,并且引入了更多可扩展的用法,获取路径会更方便。
2、常规用法
Path子类的使用,可以用该类创建文件夹和目录
有多种初始化Path
的方式,比如,使用当前工作路径
from pathlib import Path
Path.cwd() # PosixPath('/home/user/Downloads')
或者使用home()
Path.home() # PosixPath('/home/user')
使用正斜杠运算符进行路径连接
data_dir = Path(".") / "data"
csv_file = data_dir / "file.csv"
print(data_dir) # data
print(csv_file) # data/file.csv
检查路径是否存在,可以使用布尔函数 exists
data_dir.exists()
使用 is_dir
或 is_file
函数来检查是否为文件夹、文件
data_dir.is_dir()
csv_file.is_file()
绝对路径
csv_file.absolute() # PosixPath('/home/user/Downloads/data/file.csv')
转字符串
str(Path.home()) # '/home/user'
3、Path的属性
返回当前工作目录的上一级
image_file.parent # PosixPath('/home/user/Downloads/images')
获取文件名
image_file.name # 'shadousheng.png'
它将返回带有后缀的文件名,若只想要前缀,则使用stem
image_file.stem # shadousheng
只想要后缀也很简单
image_file.suffix # '.png'
如果要将路径分成多个部分,可以使用 parts
image_file.parts # ('/', 'home', 'user', 'Downloads', 'images', 'shadousheng.png')
如果希望这些组件本身就是 Path
对象,可以使用 parents
属性,它会创建一个生成器
for i in image_file.parents:
print(i)
4、目录
如何递归创建目录
new_dir.mkdir(parents=True, exist_ok=True)
要删除目录,可以使用 rmdir
,如果给定的路径对象是嵌套的,则仅删除最后一个子目录
new_dir.rmdir()
例如,使用 glob("*.txt")
查找主目录中所有文本文件
home = Path.home()
text_files = list(home.glob("*.txt"))
len(text_files) # 3
来自:还在使用os.path?Python中的Pathlib太香了