pathlib
中封装了PurePath
和Path
类,前者用于处理路径风格的字符串;后者是前者的子类,可直接处理路径。
PurePath
最甜的功能是重载了运算符,从而可以实现类似下面这种
>>> from pathlib import Path, PurePath
>>> pp = PurePath("E:/")
>>> pp
PureWindowsPath('E:/')
>>> pp/"test"
PureWindowsPath('E:/test')
对于PurePath
对象来说,可调用下面的成员或成员函数
部分 | drive [盘符], root [根路径], anchor [盘符+根路径],parent [父路径], parents [全部父路径], name [文件名]suffix [文件后缀], suffixes [所有文件后缀],stem [主文件名] |
拼拆 | parts [拆分], joinpath [拼接] |
替换 | with_name [文件名], with_suffix [后缀], with_stem [主文件名] |
风格转换 | as_posix() , as_uri() |
判断 | is_absolute , is_relative_to , is_reserved |
其中,主文件名即去除后缀之后的文件名。
PurePath
类中还有一些稍微复杂的函数,
>>> pp = PurePath("E:\Code\test.py")
# 用于匹配文件后缀
>>> pp.match("*.py")
True
# 去除基准路径
>>> pp.relative_to("E:\\")
PureWindowsPath('Code\test.py')
# 更改文件名
>>> pp.with_name('test1.py')
PureWindowsPath('E:/test1.py')
# 更改后缀名
>>> pp.with_suffix(".md")
PureWindowsPath('E:/Code\test.md')
# 更改主文件名
>>> pp.with_stem("help.md")
PureWindowsPath('E:/help.md.py')
Path
Path是PurePath的子类,在PurePath
的基础上添加了一些判定函数,
判定函数 | is_dir ,is_file ,is_fifo ,is_block_device ,is_char_device ,is_mount ,is_symlink ,is_socket |
Path
对象还可以打开并写入数据,但令人绝望的是并没有close
函数,所以并不建议使用。或者说,这个Path.open
不像是给程序员使用的,因为Path
中提供了更加便捷的读写方式read_bytes
,read_text
以及write_bytes
、write_text
。
例如
>>> p = Path(r'E:\Documents\00\0324\Test.txt')
>>> p.write_text("hello world")
11
>>> p.read_text()
'hello world'
>>>
此外,可用于直接操作文件和文件夹,提供了非常强大的文件处理功能。Path
和os
中提供的函数在功能上对应如下
os. |
pathlib |
功能 |
---|---|---|
chmod() | chmod() | 更改文件属性 |
mkdir() os.makedirs() |
mkdir() | 新建文件夹 |
rename() | rename() | 重命名 |
replace() | replace() | 重命名,若新名字已存在,则覆盖 |
rmdir() | rmdir() | 删除文件夹 |
remove() unlink() |
unlink() | 删除文件 |
getcwd() | Path.cwd() | 当前路径 |
path.abspath() | resolve() | 绝对路径 |
path.expanduser() | expanduser() home() |
系统/用户路径 |
listdir() | iterdir() | 列出所有子路径 |
path.exists() | exists() | 判定路径是否存在 |
path.isdir() | is_dir() | 判定路径是否为目录 |
path.isfile() | is_file() | 判定路径是否为文件 |
path.islink() | is_symlink() | 判定路径是否为链接 |
path.isabs() | is_absolute() | 判定路径是否为绝对路径 |
link() | hardlink_to() | 连接文件 |
symlink() | symlink_to() | 连接文件 |
readlink() | readlink() | 读取连接 |
path.join() | joinpath() | 连接路径 |
path.samefile() | samefile() | 判断路径是否相同 |
path.basename() | name | |
path.dirname() | parent | |
path.splitext() | suffix |