2020年9月30日 / 1,778次阅读 / Last Modified 2020年10月9日
一直用os.path模块处理与文件路径有关的操作,python从3.4开始提供了pathlib,是一种用OO方式处理pathname的新机制。os.path是比较low-level的接口,用string处理pathname。
pathlib中主要有两个class,PurePath和Path,后者继承前者。PurePath用来支持对纯粹的pathname的各种操作,不会接触到filesystem。而Path则实现了调用filesystem接口。
我们一般直接使用Path对象。
>>> from pathlib import Path
>>> p = Path()
>>> p.cwd()
PosixPath('/home/pi/test')
>>>
>>> p / 'abc'
PosixPath('abc')
>>>
>>> p2 = p / 'xiema'
>>> p2.resolve()
PosixPath('/home/pi/test/xiema')
>>> p2.resolve().parts
>>> p2.resolve().name
'xiema'
>>> p2.resolve().is_dir()
True
('/', 'home', 'pi', 'test', 'xiema')
>>> str(p2)
'xiema'
>>> str(p2.resolve())
'/home/pi/test/xiema'
/ : slash operator,用来直接拼接pathname。
Path对象的很多接口功能都与os.path提供的类似,有些只是名称不同。
pathlib模块的官方文档:https://docs.python.org/3/library/pathlib.html
>>> from pathlib import Path
>>> p = Path()
>>> p
PosixPath('.')
>>> p.resolve()
PosixPath('/mnt/d/test')
>>> p2 = p/'t1.txt'
>>> p2
PosixPath('t1.txt')
>>> p2.unlink()
t1.txt就被删除了!
如果是目录,要用Path.rmdir来操作。
Path.unlink(missing_ok=False)
Remove this file or symbolic link. If the path points to a directory, use Path.rmdir() instead.
If missing_ok is false (the default), FileNotFoundError is raised if the path does not exist.
If missing_ok is true, FileNotFoundError exceptions will be ignored (same behavior as the POSIX rm -f command).
Changed in version 3.8: The missing_ok parameter was added.
>>> from pathlib import Path
>>> p = Path('abc')
>>> p.resolve()
PosixPath('/mnt/d/test/abc')
>>> p.exists()
False
>>> p.mkdir()
>>> p.exists()
True
Path.mkdir有一个python3.5才加上的参数很有用,exist_ok,可以简化代码的编写:
>>> p.resolve()
PosixPath('/mnt/d/test/abc')
>>> p.exists()
True
>>> p.mkdir()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/python-3.8.5/lib/python3.8/pathlib.py", line 1284, in mkdir
self._accessor.mkdir(self, mode)
FileExistsError: [Errno 17] File exists: 'abc'
>>> p.mkdir(exist_ok=True)
>>> p.mkdir(exist_ok=True)
>>> p.mkdir(exist_ok=True)
创建已经存在路径,默认会出现FileExistsError,把exist_ok=True后,这个异常会被忽略,代码会看起来更清爽。
>>> p = Path('setup.py')
>>> with p.open() as f:
... f.readline()
...
'#!/usr/bin/env python3\n'
好稀饭...
作用相当于os.listdir(),不过Path.iterdir()返回的是一个迭代器,以及path对象。
Path.stem是文件名;
Path.suffix是文件后缀。
这两个property用起来非常方便。
-- EOF --
本文链接:https://www.pynote.net/archives/2507
《pathlib模块使用》有1条留言
前一篇:给tkinter程序添加左上角图标
后一篇:truncate函数
©Copyright 麦新杰 Since 2019 Python笔记
因为这个slash operator,我会用pathlib模块,OO的方式总是可读性更好。 [ ]