pathlib的使用方法

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 前言
  • 一、pathlib基本使用方法
    • 1.引入库并输出路径
    • 2.判断文件/目录是否存在
    • 3.遍历子目录
    • 4.筛选出子目录中以py结尾的文件
    • 5.多级目录的表示方法
    • 6.绝对路径的表示方法
    • 7.当前路径
    • 8.创建新目录
    • 9.获取父目录
    • 10.获取文件名及后缀名
    • 11.修改文件名或后缀名
  • 总结


前言

之前使用python中对文件的处理都是用os.path, os.path.dir(), os.path.join(), 遇到多层上级目录的时候就会写的很长,不够简洁。偶然看到pathlib中的Path模块,代码书写上要简洁一些。
最大的区别是:在过去,文件的路径是纯字符串,现在它会是一个pathlib.Path对象。


一、pathlib基本使用方法

1.引入库并输出路径

from pathlib import Path
file_path = Path('/home/ubuntu')
in:file_path
out:PosixPath('/home/ubuntu')

in:str(file_path)
out:'/home/ubuntu'

2.判断文件/目录是否存在

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()

3.遍历子目录

file_path = Path('/home/ubuntu')
child_dir_list = [child for child in file_path.iterdir() if child.is_dir()]

4.筛选出子目录中以py结尾的文件

file_path = Path('/home/ubuntu')
file_list = file_path.glob("*.py") #此目录查找
file_list = file_path.glob("*/*.py") #子目录查找
file_list = file_path.glob("**/*.py") #此目录及其所有子目录,递归地查找

5.多级目录的表示方法

In : Path('/') / 'home' / 'dongwm/code'
Out: PosixPath('/home/dongwm/code')

6.绝对路径的表示方法

file_path = Path('.')
file_path.resolve()
PosixPath('/home/antoine/pathlib')

7.当前路径

file_path = Path.cwd()
out:PosixPath('/home/antoine/pathlib')

8.创建新目录

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异常将被忽略.

9.获取父目录

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')

10.获取文件名及后缀名

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')

11.修改文件名或后缀名

#将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的抽象需要进一步阅读源码

你可能感兴趣的:(ubuntu,python,linux)