8.1 pathlib--面向对象设计的文件系统路径

8. 文件和目录的使用库

本库主要提供了处理磁盘文件和目录相关功能。比如有些模块读取文件属性,或者使用一个通用方式操作文件路径,或者创建一个临时文件。

8.1 pathlib--面向对象设计的文件系统路径

本模块主要提供了不同操作系统下的文件系统路径的操作方式。路径类分为纯路径操作无I/O操作的类和有I/O操作相关的类。整个路径的继承关系图如下:

如果从来没有使用过本模块里的类,以及也不清楚使用那一个类时,可以先使用Path类,它提供了一些协助操作路径的类。

纯路径操作在某种情况之下,也是有特殊的需要:

1. 比如在Unix系统下操作Windows路径,这时在Unix下面没办法使用 WindowsPath类,就可以使用PureWindowsPath类。

2. 比如只想操作路径,但不访问OS的路径相关功能。

8.1.1 基本使用

导入主要使用的类和显示当前子目录:

#python 3.4

from pathlib import Path

 

p = Path('.')

r = [x for x in p.iterdir() if x.is_dir()]

print(r)

结果输出如下:

[WindowsPath('micropython-master')]

 

查找一个目录下的文件,判断路径是否为目录,判断文件是否存在

例子:

#python 3.4

from pathlib import Path

 

p = Path('F:\\temp\\py')

print(list(p.glob('**/*.py')))

q = p / 'cal_1.py'

print(q, q.resolve(), q.exists(), q.is_dir())

结果输出如下:

[WindowsPath('F:/temp/py/bisect1.py'), WindowsPath('F:/temp/py/cal_1.py'), WindowsPath('F:/temp/py/chainmap1.py'), WindowsPath('F:/temp/py/chainmap2.py'), WindowsPath('F:/temp/py/closescreen.py'), WindowsPath('F:/temp/py/codecs1.py'), WindowsPath('F:/temp/py/complex1.py'), WindowsPath('F:/temp/py/copy1.py'), WindowsPath('F:/temp/py/datetimetz.py'), WindowsPath('F:/temp/py/dec1.py'), WindowsPath('F:/temp/py/difflib1.py'), WindowsPath('F:/temp/py/difflib2.py'), WindowsPath('F:/temp/py/difflib3.py'), WindowsPath('F:/temp/py/difflib4.py'), WindowsPath('F:/temp/py/difflib5.py')]

F:\temp\py\cal_1.py F:\temp\py\cal_1.py True False



蔡军生 QQ:9073204  深圳

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

caimouse

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值