提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
之前使用python中对文件的处理都是用os.path, os.path.dir(), os.path.join(), 遇到多层上级目录的时候就会写的很长,不够简洁。偶然看到pathlib中的Path模块,代码书写上要简洁一些。
最大的区别是:在过去,文件的路径是纯字符串,现在它会是一个pathlib.Path对象。
from pathlib import Path
file_path = Path('/home/ubuntu')
in:file_path
out:PosixPath('/home/ubuntu')
in:str(file_path)
out:'/home/ubuntu'
file_path = Path('/home/ubuntu')
file_name = Path('/home/ubuntu') / "test.py"
if file_path.is_dir()
if file_name.is_file()
if file_name.exists()
file_path = Path('/home/ubuntu')
child_dir_list = [child for child in file_path.iterdir() if child.is_dir()]
file_path = Path('/home/ubuntu')
file_list = file_path.glob("*.py") #此目录查找
file_list = file_path.glob("*/*.py") #子目录查找
file_list = file_path.glob("**/*.py") #此目录及其所有子目录,递归地查找
In : Path('/') / 'home' / 'dongwm/code'
Out: PosixPath('/home/dongwm/code')
file_path = Path('.')
file_path.resolve()
PosixPath('/home/antoine/pathlib')
file_path = Path.cwd()
out:PosixPath('/home/antoine/pathlib')
Path.mkdir(模式= 511,父母=假,exist_ok =假)
die_path = Path('1/2/3')
die_path.mkdir(parents=True, exist_ok =True)
如果parents为真,则根据需要创建此路径的任何缺少的 parent.
如果parents为 false(默认值),则缺少的 parent raise FileNotFoundError。
如果exist_ok为false(默认值),FileExistsError则在目标目录已存在时引发。
如果exist_ok为真,FileExistsError异常将被忽略.
In : p = Path('/home/antoine/pathlib')
In : p.parents[0]
Out: PosixPath('/home/antoine')
In : p.parents[1]
Out: PosixPath('/home')
In : p.parents[2]
Out: PosixPath('/')
In : p.parent
Out: PosixPath('/home/antoine')
In : p.parent.parent
Out: PosixPath('/home')
file_path = Path('/usr/local/etc/mongod.conf')
In : file_path.name
Out: 'mongod.conf'
In : file_path.suffix, file_path.stem
Out: ('.conf', 'mongod')
#将foo重命名成bar
before = Path('foo')
target = Path('bar')
before.rename(target)
In : p = Path('/home/gentoo/screenshot/abc.jpg')
In : p.with_suffix('.png')
Out: PosixPath('/home/gentoo/screenshot/abc.png')
In : p.with_name(f'123{p.suffix}')
Out: PosixPath('/home/gentoo/screenshot/123.jpg')
参考文章:https://zhuanlan.zhihu.com/p/87940289
官网:https://docs.python.org/3/library/pathlib.html#methods
pathlib.Path对os.path的抽象需要进一步阅读源码