纯路径与具体路径的区别在于,具体路径类可以对系统路径进行I/O操作,而纯路径则不可以, 那么纯路径类能做什么呢?纯路径类可以对路径进行计算,这种计算不涉及I/O操作, 比如获得文件的后缀。
from pathlib import PurePath
path = PurePath('/home/root/1.txt')
suffix = path.suffix
print(suffix) # .txt
.txt
获得文件路径的后缀,纯粹是一个字符串计算的操作,不涉及到I/O操作,
如果对路径的操作都属于这种类型的,那么用纯路径类就可以。那么,
具体路径的所谓I/O操作是什么呢,举一个简单的例子,判断路径是否存在。
想要判断一个路径是否存在,就一定需要访问操作系统,只有操作系统才知道一个路径是否存在。
在上面的代码里,不能用 path
对象去调用 exists
方法,
因为 PurePath
类根本没有这个方法,需要使用 Path
类才可以。
from pathlib import Path
path = Path('/home/root/1.txt')
suffix = path.suffix
print(suffix) # .txt
print(path.exists()) # False
.txt False
PurePath
是 Path
的父类,因此如果分不清该用纯路径类还是具体路径类,
那么使用 Path
类就好了。至于 PosixPath
和 WindowsPath
,如果也分不清应当依据什么进行选择,
那就不要选了,一劳永逸的选择 Path
就好了,Python会根据系统自动选择。
上面的代码,如果在windows平台上执行,path.__class__
的值是 pathlib.WindowsPath
,
如果是在linux系统上执行,path.__class__
的值是 pathlib.PosixPath
。
pathlib
方法与 os.path
函数对照关系
如果对 os.path
比较熟悉,那么在学习 pathlib
时,
可以参考下表中方法与函数的对照关系。
os 和 os.path |
pathlib |
---|---|
os.path.abspath() |
Path.resolve() |
os.chmod() |
Path.chmod() |
os.mkdir() |
Path.mkdir() |
os.rename() |
Path.rename() |
os.replace() |
Path.replace() |
os.rmdir() |
Path.rmdir() |
os.remove() , os.unlink() |
Path.unlink() |
os.getcwd() |
Path.cwd() |
os.path.exists() |
Path.exists() |
os.path.expanduser() |
Path.expanduser() 和 Path.home() |
os.path.isdir() |
Path.is_dir() |
os.path.isfile() |
Path.is_file() |
os.path.islink() |
Path.is_symlink() |
os.stat() |
Path.stat() , Path.owner() , Path.group() |
os.path.isabs() |
PurePath.is_absolute() |
os.path.join() |
PurePath.joinpath() |
os.path.basename() |
PurePath.name |
os.path.dirname() |
PurePath.parent |
os.path.samefile() |
Path.samefile() |
os.path.splitext() |
PurePath.suffix |
import os
path = os.path.dirname('/home/root/python/1.txt')
path = os.path.dirname(path)
print(path)
/home/root
向上回溯N层,需要调用N次 dirname
函数,着实麻烦,如果用 pathlib
,简直不要太简单。
from pathlib import Path
path = Path('/home/root/python/1.txt')
print(path.parents[1]) # /home/root
/home/root
for dir_path,subpaths,files in os.walk('./',False):
for file in files:
file_path = os.path.join(dir_path,file)
if file_path.endswith(".py"):
print(file_path)
./another_hello.py ./hello.py ./hello2.py ./hello3.py ./hello4.py
上面的代码,可以输出当前目录下所有的文件夹和文件,如果只想要某种后缀的文件,
那么需要对 file_path
的后缀进行判断,而使用 Path
的 glob
方法,将更加容易。
py_files = path.glob("**/*.py")
for filename in py_files:
print(filename)
"**"
是递归通配符,意味着对当前目录和子目录进行递归遍历,*.py
会匹配所有以 .py
结尾的文件路径。