python路径库pathlib应用

代码

from pathlib import Path
from tkinter import W

# 常用
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())

p3 = Path('t.txt')
with p3.open() as f:
    print(f.read())

p3 = Path('t.txt')
with open(p3, 'w') as f:
    f.write('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())

 

posted @ 2022-01-26 15:00  豆浆D  阅读(56)  评论(0编辑  收藏  举报