python path模块_python pathlib模块详解
借鑒于 pathlib 官方文檔 用于自己學(xué)習(xí)和記錄
使用 pathlib 模塊基本可以代替 os.path 來(lái)處理路徑。它采用了完全面向?qū)ο蟮木幊谭绞健?/p>
其包含六個(gè)類,圖片如下:
但是大體有兩類:
pure paths 路徑計(jì)算操作沒(méi)有IO功能
concrete paths 路徑計(jì)算操作和IO功能
從上圖可以看出:PurePath 類是所有類的基類
基礎(chǔ)使用
列出子目錄
>>> p = Path('.')
>>> [x for x in p.iterdir() if x.is_dir()]
[PosixPath('.hg'), PosixPath('docs'), PosixPath('dist'),
PosixPath('__pycache__'), PosixPath('build')]
###### 列出指定類型的文件
list(p.glob('**/*.py'))
###### 路徑拼接
在目錄樹中移動(dòng)
使用`/`來(lái)拼接路徑
```python
>>> p = Path('/etc')
>>> q = p / 'init.d' / 'reboot'
>>> q
WindowsPath('/etc/init.d/reboot')
>>> q.resolve()
WindowsPath('C:/etc/init.d/reboot')
>>> print(q)
\etc\init.d\reboot
>>> print(q.resolve())
C:\etc\init.d\reboot
>>>
```
###### 查詢路徑的屬性
```python
>>> q.exists() # Unix 里面這個(gè)會(huì)返回True
False
>>> q.is_dir()
False
>>>
```
###### 打開一個(gè)文件
```python
>>> with q.open() as f: f.readline()
...
FileNotFoundError: [Errno 2] No such file or directory # 如果不存在則報(bào)錯(cuò)
```
#### Pure paths 純路徑
純路徑對(duì)象提供了不實(shí)際訪問(wèn)文件系統(tǒng)的路徑處理操作。有三種方式來(lái)訪問(wèn)這些類。
###### class pathlib.**PurePath(\*pathsegments)**
>>> PurePath('setup.py')
PurePosixPath('setup.py') # Running on a Unix machine
PureWindowsPath('setup.py') # Running on a Windows machine
# 也可以用以下方式添加路徑
>>> PurePath('foo', 'some/path', 'bar')
PurePosixPath('foo/some/path/bar') # Running on a Unix machine
PureWindowsPath('foo/some/path/bar') # Running on a Windows machine
>>> PurePath(Path('foo'), Path('bar'))
PurePosixPath('foo/bar') # Running on a Unix machine
PureWindowsPath('foo/bar') # Running on a Windows machine
參數(shù)為空時(shí),返回當(dāng)前路徑
>>> PurePath()
PurePosixPath('.') # Running on a Unix machine
PureWindowsPath('.') # Running on a Windows machine
當(dāng)同時(shí)指定多個(gè)絕對(duì)路徑,則使用最后一個(gè)
>>> PurePath('/etc', '/usr', 'lib64')
PurePosixPath('/usr/lib64')
>>> PureWindowsPath('c:/Windows', 'd:bar')
PureWindowsPath('d:bar')
在 Windows 路徑中,改變本地根目錄并不會(huì)丟棄之前盤符的設(shè)置
>>> PureWindowsPath('c:/Windows', '/Program Files')
PureWindowsPath('c:/Program Files')
雙斜線和單獨(dú)的點(diǎn)都會(huì)被消除,但是雙點(diǎn) (‘..’) 不會(huì),以防改變符號(hào)鏈接的含義。
>>> PurePath('foo//bar')
PurePosixPath('foo/bar')
>>> PurePath('foo/./bar')
PurePosixPath('foo/bar')
>>> PurePath('foo/../bar')
PurePosixPath('foo/../bar')
###### class pathlib.**PurePosixPath(\*pathsegments)**
>>> PurePosixPath('/etc')
PurePosixPath('/etc')
其他操作與 PurePath 相同
class pathlib.PureWindowsPath(*pathsegments)
>>> PureWindowsPath('c:/Program Files/')
PureWindowsPath('c:/Program Files')
其他操作與 PurePath 相同
** 無(wú)論你正運(yùn)行什么系統(tǒng),你都可以實(shí)例化這些類,因?yàn)樗鼈兲峁┑牟僮鞑蛔鋈魏蜗到y(tǒng)調(diào)用 **
##### 通用性質(zhì)
路徑是不可變并可哈希的。相同風(fēng)格的路徑可以排序與比較。
>>> PurePosixPath('foo') == PurePosixPath('FOO')
False
>>> PureWindowsPath('foo') == PureWindowsPath('FOO')
True
>>> PureWindowsPath('FOO') in { PureWindowsPath('foo') }
True
>>> PureWindowsPath('C:') < PureWindowsPath('d:')
True
不同風(fēng)格的路徑比較得到不等的結(jié)果并且無(wú)法被排序:
>>> PureWindowsPath('foo') == PurePosixPath('foo')
False
>>> PureWindowsPath('foo') < PurePosixPath('foo')
Traceback (most recent call last):
File "", line 1, in
TypeError: '
##### 運(yùn)算符
斜杠操作符有助于操作子路徑
>>> p = PurePath('/etc')
>>> p
PurePosixPath('/etc')
>>> p / 'init.d' / 'apache2'
PurePosixPath('/etc/init.d/apache2')
>>> q = PurePath('bin')
>>> '/usr' / q
PurePosixPath('/usr/bin')
文件對(duì)象可用于任何接受 os.PathLike 接口實(shí)現(xiàn)的地方
>>> import os
>>> p = PurePath('/etc')
>>> os.fspath(p)
'/etc'
路徑的字符串表示法
>>> p = PurePath('/etc')
>>> str(p)
'/etc'
>>> p = PureWindowsPath('c:/Program Files')
>>> str(p)
'c:\\Program Files'
>>> bytes(p)
b'/etc' # 只推薦在 Unix下調(diào)用bytes
##### 訪問(wèn)路徑獨(dú)立組件
可以使用以下特征屬性:
PurePath.parts
返回一個(gè)元組,可以訪問(wèn)路徑的多個(gè)組件
>>> p = PurePath('/usr/bin/python3')
>>> p.parts
('/', 'usr', 'bin', 'python3')
>>> p = PureWindowsPath('c:/Program Files/PSF')
>>> p.parts
('c:\\', 'Program Files', 'PSF')
##### 方法和特征屬性
可以使用以下特征屬性:
PurePath.drive
一個(gè)表示驅(qū)動(dòng)器盤符或命名的字符串
>>> PureWindowsPath('c:/Program Files/').drive
'c:'
>>> PureWindowsPath('/Program Files/').drive
''
>>> PurePosixPath('/etc').drive
''
###### PurePath.**root**
一個(gè)表示(本地或全局)根的字符串
>>> PureWindowsPath('c:/Program Files/').root
'\\'
>>> PureWindowsPath('c:Program Files/').root
''
>>> PurePosixPath('/etc').root
'/'
###### PurePath.**anchor**
驅(qū)動(dòng)器和根的聯(lián)合
>>> PureWindowsPath('c:/Program Files/').anchor
'c:\\'
>>> PureWindowsPath('c:Program Files/').anchor
'c:'
>>> PurePosixPath('/etc').anchor
'/'
###### PurePath.**parents**
一個(gè)不可變序列,提供對(duì)路徑邏輯祖先的訪問(wèn)
>>> p = PureWindowsPath('c:/foo/bar/setup.py')
>>> p.parents[0]
PureWindowsPath('c:/foo/bar')
>>> p.parents[1]
PureWindowsPath('c:/foo')
>>> p.parents[2]
PureWindowsPath('c:/')
###### PurePath.**parent**
返回當(dāng)前路徑的父路徑
>>> p = PurePosixPath('/a/b/c/d')
>>> p.parent
PurePosixPath('/a/b/c')
>>> p = PurePosixPath('/')
>>> p.parent
PurePosixPath('/')
>>> p = PurePosixPath('.')
>>> p.parent
PurePosixPath('.')
>>> p = PurePosixPath('foo/..')
>>> p.parent
PurePosixPath('foo')
** 如果想要向上移動(dòng)任意文件系統(tǒng)路徑,推薦先使用 Path.resolve() 來(lái)解析符號(hào)鏈接以及消除 ".." 組件。**
PurePath.name
一個(gè)表示最后路徑組件的字符串,排除了驅(qū)動(dòng)器與根目錄
>>> PurePosixPath('my/library/setup.py').name
'setup.py'
###### PurePath.**suffix**
最后一個(gè)組件的文件擴(kuò)展名
>>> PurePosixPath('my/library/setup.py').suffix
'.py'
>>> PurePosixPath('my/library.tar.gz').suffix
'.gz'
>>> PurePosixPath('my/library').suffix
''
###### PurePath.**suffixes**
路徑的文件擴(kuò)展名列表
>>> PurePosixPath('my/library.tar.gar').suffixes
['.tar', '.gar']
>>> PurePosixPath('my/library.tar.gz').suffixes
['.tar', '.gz']
>>> PurePosixPath('my/library').suffixes
[]
###### PurePath.**stem**
最后一個(gè)路徑組件,除去后綴
>>> PurePosixPath('my/library.tar.gz').stem
'library.tar'
>>> PurePosixPath('my/library.tar').stem
'library'
>>> PurePosixPath('my/library').stem
'library'
###### PurePath.**as_posix()**
返回使用正斜杠(/)的路徑字符串
>>> p = PureWindowsPath('c:\\windows')
>>> str(p)
'c:\\windows'
>>> p.as_posix()
'c:/windows'
###### PurePath.**as_uri()**
將路徑表示為 file URL的格式。如果并非絕對(duì)路徑,拋出 ValueError。
>>> p = PurePosixPath('/etc/passwd')
>>> p.as_uri()
'file:///etc/passwd'
>>> p = PureWindowsPath('c:/Windows')
>>> p.as_uri()
'file:///c:/Windows'
###### PurePath.**is_absolute()**
返回此路徑是否為絕對(duì)路徑。如果路徑同時(shí)擁有驅(qū)動(dòng)器符與根路徑(如果風(fēng)格允許)則將被認(rèn)作絕對(duì)路徑。
>>> PurePosixPath('/a/b').is_absolute()
True
>>> PurePosixPath('a/b').is_absolute()
False
>>> PureWindowsPath('c:/a/b').is_absolute()
True
>>> PureWindowsPath('/a/b').is_absolute()
False
>>> PureWindowsPath('c:').is_absolute()
False
###### PurePath.**is_reserved()**
PureWindowsPath,如果路徑是被 Windows 保留的則返回 True,否則 False。在 PurePosixPath,總是返回 False。
>>> PureWindowsPath('nul').is_reserved()
True
>>> PurePosixPath('nul').is_reserved()
False
###### PurePath.**joinpath(\*other)**
調(diào)用此方法等同于將每個(gè) other 參數(shù)中的項(xiàng)目連接在一起
>>> PurePosixPath('/etc').joinpath('passwd')
PurePosixPath('/etc/passwd')
>>> PurePosixPath('/etc').joinpath(PurePosixPath('passwd'))
PurePosixPath('/etc/passwd')
>>> PurePosixPath('/etc').joinpath('init.d', 'apache2')
PurePosixPath('/etc/init.d/apache2')
>>> PureWindowsPath('c:').joinpath('/Program Files')
PureWindowsPath('c:/Program Files')
###### PurePath.**match(pattern)**
將此路徑與提供的通配符風(fēng)格的模式匹配。如果匹配成功則返回 True,否則返回 False。
如果 pattern 是相對(duì)的,則路徑可以是相對(duì)路徑或絕對(duì)路徑,并且匹配是從右側(cè)完成的,例如:
>>> PurePath('a/b.py').match('*.py')
True
>>> PurePath('/a/b/c.py').match('b/*.py')
True
>>> PurePath('/a/b/c.py').match('a/*.py')
False
如果 pattern 是絕對(duì)的,則路徑必須是絕對(duì)的,并且路徑必須完全匹配:
>>> PurePath('/a.py').match('/*.py')
True
>>> PurePath('a/b.py').match('/*.py')
False
# 大小寫的區(qū)分
>>> PureWindowsPath('b.py').match('*.PY')
True
###### PurePath.**relative_to(\*other)**
計(jì)算此路徑相對(duì) other 表示路徑的版本。如果不可計(jì)算,則拋出 ValueError:
```python
>>> p = PurePosixPath('/etc/passwd')
>>> p.relative_to('/')
PurePosixPath('etc/passwd')
>>> p.relative_to('/etc')
PurePosixPath('passwd')
>>> p.relative_to('/usr')
Traceback (most recent call last):
File "", line 1, in File "pathlib.py", line 694, in relative_to
.format(str(self), str(formatted)))
ValueError: '/etc/passwd' does not start with '/usr'
```
###### PurePath.**with_name(name)**
返回一個(gè)新的路徑并修改 name。如果原本路徑?jīng)]有 name,ValueError 被拋出
>>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
>>> p.with_name('setup.py')
PureWindowsPath('c:/Downloads/setup.py')
>>> p = PureWindowsPath('c:/')
>>> p.with_name('setup.py')
Traceback (most recent call last):
File "", line 1, in
File "/home/antoine/cpython/default/Lib/pathlib.py", line 751, in with_name
raise ValueError("%r has an empty name" % (self,))
ValueError: PureWindowsPath('c:/') has an empty name
###### PurePath.**with_suffix(suffix)**
返回一個(gè)新的路徑并修改后綴 suffix。如果原本的路徑?jīng)]有后綴,新的 suffix 則被追加以代替。如果 suffix 是空字符串,則原本的后綴被移除:
```python
>>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
>>> p.with_suffix('.bz2')
PureWindowsPath('c:/Downloads/pathlib.tar.bz2')
>>> p = PureWindowsPath('README')
>>> p.with_suffix('.txt')
PureWindowsPath('README.txt')
>>> p = PureWindowsPath('README.txt')
>>> p.with_suffix('')
PureWindowsPath('README')
```
##### Path 具體路徑
具體路徑是純路徑的子類。除了后者提供的操作之外,它們還提供了對(duì)路徑對(duì)象進(jìn)行系統(tǒng)調(diào)用的方法。
有以下三種方法可以實(shí)例化具體路徑:
class pathlib.Path(*pathsegments)
一個(gè) PurePath 的子類,此類以當(dāng)前系統(tǒng)的路徑風(fēng)格表示路徑(實(shí)例化為 PosixPath 或 WindowsPath):
>>> Path('setup.py')
PosixPath('setup.py') # Unix 系統(tǒng)
WindowsPath('setup.py') # Windows 系統(tǒng)
###### class pathlib.**PosixPath(*pathsegments)**
>>> PosixPath('/etc')
PosixPath('/etc')
###### class pathlib.**WindowsPath(*pathsegments)**
>>> WindowsPath('c:/Program Files/')
WindowsPath('c:/Program Files')
方法
除純路徑方法外,具體路徑還提供以下方法。
classmethod Path.cwd()
返回一個(gè)新的表示當(dāng)前目錄的路徑對(duì)象,和 os.getcwd() 返回的相同
>>> Path.cwd()
PosixPath('/home/antoine/pathlib')
###### classmethod Path.**home()**
返回一個(gè)表示當(dāng)前用戶根目錄的新路徑對(duì)象,和 os.path.expanduser() 構(gòu)造含 ~ 路徑返回的相同
>>> Path.home()
PosixPath('/home/antoine')
###### Path.**stat()**
返回此路徑的信息(類似于 os.stat())。
>>> p = Path('setup.py')
>>> p.stat().st_size
956
>>> p.stat().st_mtime
1327883547.852554
###### Path.**chmod(mode)**
改變文件的模式和權(quán)限,和 os.chmod() 一樣:
>>> p = Path('setup.py')
>>> p.stat().st_mode
33277
>>> p.chmod(0o444)
>>> p.stat().st_mode
33060
###### Path.**exists()**
此路徑是否指向一個(gè)已存在的文件或目錄
>>> Path('.').exists()
True
>>> Path('setup.py').exists()
True
>>> Path('/etc').exists()
True
>>> Path('nonexistentfile').exists()
False
###### Path.**expanduser()**
返回展開了根目錄與~的構(gòu)造,和 os.path.expanduser() 一樣:
>>> p = PosixPath('~/films/Monty Python')
>>> p.expanduser()
PosixPath('/home/eric/films/Monty Python')
###### Path.**glob(pattern)**
生成所有匹配 pattern 的文件
>>> sorted(Path('.').glob('*.py'))
[PosixPath('pathlib.py'), PosixPath('setup.py'), PosixPath('test_pathlib.py')]
>>> sorted(Path('.').glob('*/*.py'))
[PosixPath('docs/conf.py')]
“**” 模式表示 此目錄以及所有子目錄
>>> sorted(Path('.').glob('**/*.py'))
[PosixPath('build/lib/pathlib.py'),
PosixPath('docs/conf.py'),
PosixPath('pathlib.py'),
PosixPath('setup.py'),
PosixPath('test_pathlib.py')]
###### Path.**group()**
返回?fù)碛写宋募挠脩艚M。
Path.is_dir()
如果路徑指向一個(gè)目錄(或者一個(gè)指向目錄的符號(hào)鏈接)則返回 True,如果指向其他類型的文件則返回 False
當(dāng)路徑不存在或者是一個(gè)破損的符號(hào)鏈接時(shí)也會(huì)返回 False
Path.is_file()
如果路徑指向一個(gè)正常的文件(或者一個(gè)指向正常文件的符號(hào)鏈接)則返回 True,如果指向其他類型的文件則返回 False。
當(dāng)路徑不存在或者是一個(gè)破損的符號(hào)鏈接時(shí)也會(huì)返回 False
Path.is_symlink()
如果路徑指向符號(hào)鏈接則返回 True, 否則 False。
如果路徑不存在也返回 False
Path.is_socket()
如果路徑指向一個(gè) Unix socket 文件(或者指向 Unix socket 文件的符號(hào)鏈接)則返回 True,如果指向其他類型的文件則返回 False。
當(dāng)路徑不存在或者是一個(gè)破損的符號(hào)鏈接時(shí)也會(huì)返回 False
Path.is_fifo()
如果路徑指向一個(gè)先進(jìn)先出存儲(chǔ)(或者指向先進(jìn)先出存儲(chǔ)的符號(hào)鏈接)則返回 True ,指向其他類型的文件則返回 False。
當(dāng)路徑不存在或者是一個(gè)破損的符號(hào)鏈接時(shí)也會(huì)返回 False
Path.is_block_device()
如果文件指向一個(gè)塊設(shè)備(或者指向塊設(shè)備的符號(hào)鏈接)則返回 True,指向其他類型的文件則返回 False。
當(dāng)路徑不存在或者是一個(gè)破損的符號(hào)鏈接時(shí)也會(huì)返回 False
Path.is_char_device()
如果路徑指向一個(gè)字符設(shè)備(或指向字符設(shè)備的符號(hào)鏈接)則返回 True,指向其他類型的文件則返回 False。
當(dāng)路徑不存在或者是一個(gè)破損的符號(hào)鏈接時(shí)也會(huì)返回 False
Path.iterdir()
當(dāng)路徑指向一個(gè)目錄時(shí),產(chǎn)生該路徑下的對(duì)象的路徑
>>> p = Path('docs')
>>> for child in p.iterdir(): child
...
PosixPath('docs/conf.py')
PosixPath('docs/_templates')
PosixPath('docs/make.bat')
PosixPath('docs/index.rst')
PosixPath('docs/_build')
PosixPath('docs/_static')
PosixPath('docs/Makefile')
###### Path.**mkdir(mode=0o777, parents=False, exist_ok=False)**
創(chuàng)建目錄
Path.open(mode='r', buffering=-1, encoding=None, errors=None, newline=None)
打開路徑指向的文件
>>> p = Path('setup.py')
>>> with p.open() as f:
... f.readline()
...
'#!/usr/bin/env python3\n'
###### Path.**owner()**
返回?fù)碛写宋募挠脩裘H绻募?UID 無(wú)法在系統(tǒng)數(shù)據(jù)庫(kù)中找到,則拋出 KeyError。
Path.read_bytes()
以字節(jié)對(duì)象的形式返回路徑指向的文件的二進(jìn)制內(nèi)容:
>>> p = Path('my_binary_file')
>>> p.write_bytes(b'Binary file contents')
20
>>> p.read_bytes()
b'Binary file contents'
###### Path.**read_text(encoding=None, errors=None)**
以字符串形式返回路徑指向的文件的解碼后文本內(nèi)容
>>> p = Path('my_text_file')
>>> p.write_text('Text file contents')
18
>>> p.read_text()
'Text file contents'
###### Path.**rename(target)**
使用給定的 target 將文件重命名
>>> p = Path('foo')
>>> p.open('w').write('some text')
9
>>> target = Path('bar')
>>> p.rename(target)
>>> target.open().read()
'some text'
###### Path.**replace(target)**
使用給定的 target 重命名文件或目錄。
Path.resolve(target)
將路徑絕對(duì)化,解析任何符號(hào)鏈接。返回新的路徑對(duì)象:
>>> p = Path()
>>> p
PosixPath('.')
>>> p.resolve()
PosixPath('/home/antoine/pathlib')
# ‘..’組件也會(huì)被消除
>>> p = Path('docs/../setup.py')
>>> p.resolve()
PosixPath('/home/antoine/pathlib/setup.py')
###### Path.**rglob(pattern)**
與給定模式前面添加'**'一樣調(diào)用 Path.glob():
>>> sorted(Path().rglob("*.py"))
[PosixPath('build/lib/pathlib.py'),
PosixPath('docs/conf.py'),
PosixPath('pathlib.py'),
PosixPath('setup.py'),
PosixPath('test_pathlib.py')]
###### Path.**rmdir()**
移除此目錄。此目錄必須為空的。
Path.samefile(other_path)
返回此目錄是否指向與可能是字符串或者另一個(gè)路徑對(duì)象的 other_path 相同的文件。
>>> p = Path('spam')
>>> q = Path('eggs')
>>> p.samefile(q)
False
>>> p.samefile('spam')
True
###### Path.**symlink_to(target, target_is_directory=False)**
將此路徑創(chuàng)建為指向 target 的符號(hào)鏈接。在 Windows 下,如果鏈接的目標(biāo)是一個(gè)目錄則 target_is_directory 必須為 true (默認(rèn)為 False)。在 POSIX 下, target_is_directory 的值將被忽略。
>>> p = Path('mylink')
>>> p.symlink_to('setup.py')
>>> p.resolve()
PosixPath('/home/antoine/pathlib/setup.py')
>>> p.stat().st_size
956
>>> p.lstat().st_size
8
###### Path.**touch(mode=0o666, exist_ok=True)**
將給定的路徑創(chuàng)建為文件。
如果給出了 mode 它將與當(dāng)前進(jìn)程的 umask 值合并以確定文件的模式和訪問(wèn)標(biāo)志。如果文件已經(jīng)存在,則當(dāng) exist_ok 為 true 則函數(shù)仍會(huì)成功(并且將它的修改事件更新為當(dāng)前事件),否則拋出 FileExistsError。
Path.unlink()
移除此文件或符號(hào)鏈接。如果路徑指向目錄,則用 Path.rmdir() 代替。
Path.write_bytes(data)
將文件以二進(jìn)制模式打開,寫入 data 并關(guān)閉:
>>> p = Path('my_binary_file')
>>> p.write_bytes(b'Binary file contents')
20
>>> p.read_bytes()
b'Binary file contents'
###### Path.**write_text(data, encoding=None, errors=None)**
將文件以文本模式打開,寫入 data 并關(guān)閉:
>>> p = Path('my_text_file')
>>> p.write_text('Text file contents')
18
>>> p.read_text()
'Text file contents'
總結(jié)
以上是生活随笔為你收集整理的python path模块_python pathlib模块详解的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: android 代码设置dialog 全
- 下一篇: python的flask实现第三方登录怎