编程语言
首页 > 编程语言> > python路径库pathlib应用

python路径库pathlib应用

作者:互联网

代码

from pathlib import Path

# 常用
p = Path('./util')
print(type(p), p)
print(type(str(p)), p)
print(p.exists())
print(p.is_dir())

# 路径组合
p2 = p / 'actions.py'
print(type(p2), p2)

# 文件名字及后缀
p = Path('util/actions.py')
print(p.name)
print(p.stem)
print(p.suffix)

# 文件打开
p3 = Path('t.txt')
with open(p2) as f:
print(f.read())
# f.wright('abc')

# 文件后缀
p = Path('util/actions.py.gz')
print(p.suffix) # .gz
print(p.suffixes) # ['.py', '.gz']

# 文件父目录
p = Path('test/pw/util/actions.py')
print(p.parent) # test/pw/util
print(p.parents[0]) # test/pw/util
print(p.parents[1]) # test/pw
print(p.parents[2]) # test

# 其他用法
print([x for x in p.iterdir() if x.is_dir()]) # 遍历p目录下的所有文件夹
print(list(p.glob('**/*.py'))) # 搜索当前路径下所有.py结尾的文件

# windows调用
p = Path('C:/Users/Administrator/Desktop/Pexe')
print(p)
print(p.exists())

 

标签:py,python,路径,pathlib,actions,util,test,print,Path
来源: https://www.cnblogs.com/soymilk2019/p/15846600.html