标签:admin type tor nts path str from docx 文件
导入主要的类:
>>> from pathlib import Path
创建Path对象:
>>> p = Path('C:/Users/Administrator/Desktop/text.txt')
打印Path对象中的路径及Path对象类型:
>>> print(p, type(p))
C:\Users\Administrator\Desktop\text.txt <class 'pathlib.WindowsPath'>
引用路径时需先将对象转化为str类型
str(p)
列出子目录:
>>> p = Path('C:/Users/Administrator/Desktop')
>>> [x for x in p.iterdir() if p.is_dir()]
[WindowsPath('C:/Users/Administrator/Desktop/新建文件夹'),
WindowsPath('C:/Users/Administrator/Desktop/新建 Microsoft Word 文档.docx'),
WindowsPath('C:/Users/Administrator/Desktop/Xshell.lnk')
WindowsPath('C:/Users/Administrator/Desktop/note.exe')]
列出当前目录树中(p目录及子孙目录中)的所有txt文件:
>>> p = Path('C:/Users/Administrator/Desktop')
>>> list(p.glob('**/*.txt'))
[WindowsPath('C:/Users/Administrator/Desktop/reg.txt'),
WindowsPath('C:/Users/Administrator/Desktop/sample.txt'),
WindowsPath('C:/Users/Administrator/Desktop/text.txt'),
WindowsPath('C:/Users/Administrator/Desktop/新建文件夹/新建文本文档.txt'),
WindowsPath('C:/Users/Administrator/Desktop/新建文件夹/新建文件夹1/新建文本文档1.txt')]
操作一个目录树:
>>> p = Path('C:/Users/Administrator/Desktop')
>>> q = p / 'newfolder'
>>> q
WindowsPath('C:/Users/Administrator/Desktop/newfolder')
父路径Path.parent
,返回<class ‘pathlib.WindowsPath‘>(windows10系统)
所有p的祖辈路径p.parents
,返回<class ‘pathlib._PathParents‘>
标签:admin type tor nts path str from docx 文件
原文地址:https://www.cnblogs.com/juneman/p/8971446.html