pathlib --- 面向?qū)ο蟮奈募到y(tǒng)路徑?

3.4 新版功能.

源代碼 Lib/pathlib.py


該模塊提供表示文件系統(tǒng)路徑的類,其語(yǔ)義適用于不同的操作系統(tǒng)。路徑類被分為提供純計(jì)算操作而沒(méi)有 I/O 的 純路徑,以及從純路徑繼承而來(lái)但提供 I/O 操作的 具體路徑。

../images/pathlib-inheritance.png

如果以前從未用過(guò)此模塊,或不確定哪個(gè)類適合完成任務(wù),那要用的可能就是 Path。它在運(yùn)行代碼的平臺(tái)上實(shí)例化為 具體路徑。

在一些用例中純路徑很有用,例如:

  1. 如果你想要在 Unix 設(shè)備上操作 Windows 路徑(或者相反)。你不應(yīng)在 Unix 上實(shí)例化一個(gè) WindowsPath,但是你可以實(shí)例化 PureWindowsPath。

  2. 你只想操作路徑但不想實(shí)際訪問(wèn)操作系統(tǒng)。在這種情況下,實(shí)例化一個(gè)純路徑是有用的,因?yàn)樗鼈儧](méi)有任何訪問(wèn)操作系統(tǒng)的操作。

參見(jiàn)

PEP 428:pathlib 模塊 -- 面向?qū)ο蟮牡奈募到y(tǒng)路徑。

參見(jiàn)

對(duì)于底層的路徑字符串操作,你也可以使用 os.path 模塊。

基礎(chǔ)使用?

導(dǎo)入主類:

>>>
>>> from pathlib import Path

列出子目錄:

>>>
>>> p = Path('.')
>>> [x for x in p.iterdir() if x.is_dir()]
[PosixPath('.hg'), PosixPath('docs'), PosixPath('dist'),
 PosixPath('__pycache__'), PosixPath('build')]

列出當(dāng)前目錄樹(shù)下的所有 Python 源代碼文件:

>>>
>>> list(p.glob('**/*.py'))
[PosixPath('test_pathlib.py'), PosixPath('setup.py'),
 PosixPath('pathlib.py'), PosixPath('docs/conf.py'),
 PosixPath('build/lib/pathlib.py')]

在目錄樹(shù)中移動(dòng):

>>>
>>> p = Path('/etc')
>>> q = p / 'init.d' / 'reboot'
>>> q
PosixPath('/etc/init.d/reboot')
>>> q.resolve()
PosixPath('/etc/rc.d/init.d/halt')

查詢路徑的屬性:

>>>
>>> q.exists()
True
>>> q.is_dir()
False

打開(kāi)一個(gè)文件:

>>>
>>> with q.open() as f: f.readline()
...
'#!/bin/bash\n'

純路徑?

純路徑對(duì)象提供了不實(shí)際訪問(wèn)文件系統(tǒng)的路徑處理操作。有三種方式來(lái)訪問(wèn)這些類,也是不同的風(fēng)格:

class pathlib.PurePath(*pathsegments)?

一個(gè)通用的類,代表當(dāng)前系統(tǒng)的路徑風(fēng)格(實(shí)例化為 PurePosixPath 或者 PureWindowsPath):

>>>
>>> PurePath('setup.py')      # Running on a Unix machine
PurePosixPath('setup.py')

每一個(gè) pathsegments 的元素可能是一個(gè)代表路徑片段的字符串,一個(gè)返回字符串的實(shí)現(xiàn)了 os.PathLike 接口的對(duì)象,或者另一個(gè)路徑對(duì)象:

>>>
>>> PurePath('foo', 'some/path', 'bar')
PurePosixPath('foo/some/path/bar')
>>> PurePath(Path('foo'), Path('bar'))
PurePosixPath('foo/bar')

當(dāng) pathsegments 為空的時(shí)候,假定為當(dāng)前目錄:

>>>
>>> PurePath()
PurePosixPath('.')

當(dāng)給出一些絕對(duì)路徑,最后一位將被當(dāng)作錨(模仿 os.path.join() 的行為):

>>>
>>> PurePath('/etc', '/usr', 'lib64')
PurePosixPath('/usr/lib64')
>>> PureWindowsPath('c:/Windows', 'd:bar')
PureWindowsPath('d:bar')

但是,在 Windows 路徑中,改變本地根目錄并不會(huì)丟棄之前盤(pán)符的設(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')

(一個(gè)很 na?ve 的做法是讓 PurePosixPath('foo/../bar') 等同于 PurePosixPath('bar'),如果 foo 是一個(gè)指向其他目錄的符號(hào)鏈接那么這個(gè)做法就將出錯(cuò))

純路徑對(duì)象實(shí)現(xiàn)了 os.PathLike 接口,允許它們?cè)谌魏谓邮艽私涌诘牡胤绞褂谩?/p>

在 3.6 版更改: 添加了 os.PathLike 接口支持。

class pathlib.PurePosixPath(*pathsegments)?

一個(gè) PurePath 的子類,路徑風(fēng)格不同于 Windows 文件系統(tǒng):

>>>
>>> PurePosixPath('/etc')
PurePosixPath('/etc')

pathsegments 參數(shù)的指定和 PurePath 相同。

class pathlib.PureWindowsPath(*pathsegments)?

PurePath 的一個(gè)子類,路徑風(fēng)格為 Windows 文件系統(tǒng)路徑:

>>>
>>> PureWindowsPath('c:/Program Files/')
PureWindowsPath('c:/Program Files')

pathsegments 參數(shù)的指定和 PurePath 相同。

無(wú)論你正運(yùn)行什么系統(tǒng),你都可以實(shí)例化這些類,因?yàn)樗鼈兲峁┑牟僮鞑蛔鋈魏蜗到y(tǒng)調(diào)用。

通用性質(zhì)?

路徑是不可變并可哈希的。相同風(fēng)格的路徑可以排序與比較。這些性質(zhì)尊重對(duì)應(yīng)風(fēng)格的大小寫(xiě)轉(zhuǎn)換語(yǔ)義:

>>>
>>> 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 "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'PureWindowsPath' and 'PurePosixPath'

運(yùn)算符?

斜杠 / 操作符有助于創(chuàng)建子路徑,就像 os.path.join() 一樣:

>>>
>>> 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'

路徑的字符串表示法為它自己原始的文件系統(tǒng)路徑(以原生形式,例如在 Windows 下使用反斜杠)。你可以傳遞給任何需要字符串形式路徑的函數(shù)。

>>>
>>> p = PurePath('/etc')
>>> str(p)
'/etc'
>>> p = PureWindowsPath('c:/Program Files')
>>> str(p)
'c:\\Program Files'

類似地,在路徑上調(diào)用 bytes 將原始文件系統(tǒng)路徑作為字節(jié)對(duì)象給出,就像被 os.fsencode() 編碼一樣:

>>>
>>> bytes(p)
b'/etc'

備注

只推薦在 Unix 下調(diào)用 bytes。在 Windows, unicode 形式是文件系統(tǒng)路徑的規(guī)范表示法。

訪問(wèn)個(gè)別部分?

為了訪問(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')

(注意盤(pán)符和本地根目錄是如何重組的)

方法和特征屬性?

純路徑提供以下方法和特征屬性:

PurePath.drive?

一個(gè)表示驅(qū)動(dòng)器盤(pán)符或命名的字符串,如果存在:

>>>
>>> PureWindowsPath('c:/Program Files/').drive
'c:'
>>> PureWindowsPath('/Program Files/').drive
''
>>> PurePosixPath('/etc').drive
''

UNC 分享也被認(rèn)作驅(qū)動(dòng)器:

>>>
>>> PureWindowsPath('//host/share/foo.txt').drive
'\\\\host\\share'
PurePath.root?

一個(gè)表示(本地或全局)根的字符串,如果存在:

>>>
>>> PureWindowsPath('c:/Program Files/').root
'\\'
>>> PureWindowsPath('c:Program Files/').root
''
>>> PurePosixPath('/etc').root
'/'

UNC 分享一樣擁有根:

>>>
>>> PureWindowsPath('//host/share').root
'\\'
PurePath.anchor?

驅(qū)動(dòng)器和根的聯(lián)合:

>>>
>>> PureWindowsPath('c:/Program Files/').anchor
'c:\\'
>>> PureWindowsPath('c:Program Files/').anchor
'c:'
>>> PurePosixPath('/etc').anchor
'/'
>>> PureWindowsPath('//host/share').anchor
'\\\\host\\share\\'
PurePath.parents?

An immutable sequence providing access to the logical ancestors of the path:

>>>
>>> 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:/')

在 3.10 版更改: parents 序列現(xiàn)在支持 切片 負(fù)的索引值。

PurePath.parent?

此路徑的邏輯父路徑:

>>>
>>> p = PurePosixPath('/a/b/c/d')
>>> p.parent
PurePosixPath('/a/b/c')

你不能超過(guò)一個(gè) anchor 或空路徑:

>>>
>>> p = PurePosixPath('/')
>>> p.parent
PurePosixPath('/')
>>> p = PurePosixPath('.')
>>> p.parent
PurePosixPath('.')

備注

這是一個(gè)單純的詞法操作,因此有以下行為:

>>>
>>> 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'

UNC 驅(qū)動(dòng)器名不被考慮:

>>>
>>> PureWindowsPath('//some/share/setup.py').name
'setup.py'
>>> PureWindowsPath('//some/share').name
''
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
>>> PureWindowsPath('//some/share').is_absolute()
True
PurePath.is_relative_to(*other)?

返回此路徑是否相對(duì)于 other 的路徑。

>>>
>>> p = PurePath('/etc/passwd')
>>> p.is_relative_to('/etc')
True
>>> p.is_relative_to('/usr')
False

3.9 新版功能.

PurePath.is_reserved()?

PureWindowsPath,如果路徑是被 Windows 保留的則返回 True,否則 False。在 PurePosixPath,總是返回 False。

>>>
>>> PureWindowsPath('nul').is_reserved()
True
>>> PurePosixPath('nul').is_reserved()
False

當(dāng)保留路徑上的文件系統(tǒng)被調(diào)用,則可能出現(xiàn)玄學(xué)失敗或者意料之外的效應(yīng)。

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

與其他方法一樣,是否大小寫(xiě)敏感遵循平臺(tái)的默認(rèn)規(guī)則:

>>>
>>> PurePosixPath('b.py').match('*.PY')
False
>>> PureWindowsPath('b.py').match('*.PY')
True
PurePath.relative_to(*other)?

計(jì)算此路徑相對(duì) other 表示路徑的版本。如果不可計(jì)算,則拋出 ValueError:

>>>
>>> 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 "<stdin>", line 1, in <module>
  File "pathlib.py", line 694, in relative_to
    .format(str(self), str(formatted)))
ValueError: '/etc/passwd' is not in the subpath of '/usr' OR one path is relative and the other absolute.

注意:此函數(shù)是 PurePath 的一部分并且適用于字符串。 它不會(huì)檢查或訪問(wèn)下層的文件結(jié)構(gòu)。

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 "<stdin>", line 1, in <module>
  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_stem(stem)?

返回一個(gè)帶有修改后 stem 的新路徑。 如果原路徑?jīng)]有名稱,則會(huì)引發(fā) ValueError:

>>>
>>> p = PureWindowsPath('c:/Downloads/draft.txt')
>>> p.with_stem('final')
PureWindowsPath('c:/Downloads/final.txt')
>>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
>>> p.with_stem('lib')
PureWindowsPath('c:/Downloads/lib.gz')
>>> p = PureWindowsPath('c:/')
>>> p.with_stem('')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/antoine/cpython/default/Lib/pathlib.py", line 861, in with_stem
    return self.with_name(stem + self.suffix)
  File "/home/antoine/cpython/default/Lib/pathlib.py", line 851, in with_name
    raise ValueError("%r has an empty name" % (self,))
ValueError: PureWindowsPath('c:/') has an empty name

3.9 新版功能.

PurePath.with_suffix(suffix)?

返回一個(gè)新的路徑并修改 suffix。如果原本的路徑?jīng)]有后綴,新的 suffix 則被追加以代替。如果 suffix 是空字符串,則原本的后綴被移除:

>>>
>>> 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')

具體路徑?

具體路徑是純路徑的子類。除了后者提供的操作之外,它們還提供了對(duì)路徑對(duì)象進(jìn)行系統(tǒng)調(diào)用的方法。有三種方法可以實(shí)例化具體路徑:

class pathlib.Path(*pathsegments)?

一個(gè) PurePath 的子類,此類以當(dāng)前系統(tǒng)的路徑風(fēng)格表示路徑(實(shí)例化為 PosixPathWindowsPath):

>>>
>>> Path('setup.py')
PosixPath('setup.py')

pathsegments 參數(shù)的指定和 PurePath 相同。

class pathlib.PosixPath(*pathsegments)?

一個(gè) PathPurePosixPath 的子類,此類表示一個(gè)非 Windows 文件系統(tǒng)的具體路徑:

>>>
>>> PosixPath('/etc')
PosixPath('/etc')

pathsegments 參數(shù)的指定和 PurePath 相同。

class pathlib.WindowsPath(*pathsegments)?

PathPureWindowsPath 的子類,從類表示一個(gè) Windows 文件系統(tǒng)的具體路徑:

>>>
>>> WindowsPath('c:/Program Files/')
WindowsPath('c:/Program Files')

pathsegments 參數(shù)的指定和 PurePath 相同。

你只能實(shí)例化與當(dāng)前系統(tǒng)風(fēng)格相同的類(允許系統(tǒng)調(diào)用作用于不兼容的路徑風(fēng)格可能在應(yīng)用程序中導(dǎo)致缺陷或失?。?

>>>
>>> import os
>>> os.name
'posix'
>>> Path('setup.py')
PosixPath('setup.py')
>>> PosixPath('setup.py')
PosixPath('setup.py')
>>> WindowsPath('setup.py')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pathlib.py", line 798, in __new__
    % (cls.__name__,))
NotImplementedError: cannot instantiate 'WindowsPath' on your system

方法?

除純路徑方法外,實(shí)體路徑還提供以下方法。 如果系統(tǒng)調(diào)用失?。ɡ缫?yàn)槁窂讲淮嬖冢┻@些方法中許多都會(huì)引發(fā) OSError。

在 3.8 版更改: 對(duì)于包含 OS 層級(jí)無(wú)法表示字符的路徑,exists(), is_dir(), is_file(), is_mount(), is_symlink(), is_block_device(), is_char_device(), is_fifo(), is_socket() 現(xiàn)在將返回 False 而不是引發(fā)異常。

classmethod Path.cwd()?

返回一個(gè)新的表示當(dāng)前目錄的路徑對(duì)象(和 os.getcwd() 返回的相同):

>>>
>>> Path.cwd()
PosixPath('/home/antoine/pathlib')
classmethod Path.home()?

返回一個(gè)表示用戶家目錄的新路徑對(duì)象(與帶 ~ 構(gòu)造的 os.path.expanduser() 所返回的相同)。 如果無(wú)法解析家目錄,則會(huì)引發(fā) RuntimeError。

>>>
>>> Path.home()
PosixPath('/home/antoine')

3.5 新版功能.

Path.stat(*, follow_symlinks=True)?

返回一個(gè) os.stat_result 對(duì)象,其中包含有關(guān)此路徑的信息,例如 os.stat()。 結(jié)果會(huì)在每次調(diào)用此方法時(shí)重新搜索。

此方法通常會(huì)跟隨符號(hào)鏈接;要對(duì) symlink 使用 stat 請(qǐng)?zhí)砑訁?shù) follow_symlinks=False,或者使用 lstat()。

>>>
>>> p = Path('setup.py')
>>> p.stat().st_size
956
>>> p.stat().st_mtime
1327883547.852554

在 3.10 版更改: 增加了 follow_symlinks 形參。

Path.chmod(mode, *, follow_symlinks=True)?

改變文件模式和權(quán)限,和 os.chmod() 一樣。

此方法通常會(huì)跟隨符號(hào)鏈接。 某些 Unix 變種支持改變 symlink 本身的權(quán)限;在這些平臺(tái)上你可以添加參數(shù) follow_symlinks=False,或者使用 lchmod()

>>>
>>> p = Path('setup.py')
>>> p.stat().st_mode
33277
>>> p.chmod(0o444)
>>> p.stat().st_mode
33060

在 3.10 版更改: 增加了 follow_symlinks 形參。

Path.exists()?

此路徑是否指向一個(gè)已存在的文件或目錄:

>>>
>>> Path('.').exists()
True
>>> Path('setup.py').exists()
True
>>> Path('/etc').exists()
True
>>> Path('nonexistentfile').exists()
False

備注

如果路徑指向一個(gè)符號(hào)鏈接, exists() 返回此符號(hào)鏈接是否指向存在的文件或目錄。

Path.expanduser()?

返回帶有擴(kuò)展 ~~user 構(gòu)造的新路徑,與 os.path.expanduser() 所返回的相同。 如果無(wú)法解析家目錄,則會(huì)引發(fā) RuntimeError。

>>>
>>> p = PosixPath('~/films/Monty Python')
>>> p.expanduser()
PosixPath('/home/eric/films/Monty Python')

3.5 新版功能.

Path.glob(pattern)?

解析相對(duì)于此路徑的通配符 pattern,產(chǎn)生所有匹配的文件:

>>>
>>> sorted(Path('.').glob('*.py'))
[PosixPath('pathlib.py'), PosixPath('setup.py'), PosixPath('test_pathlib.py')]
>>> sorted(Path('.').glob('*/*.py'))
[PosixPath('docs/conf.py')]

pattern 的形式與 fnmatch 的相同,還增加了 "**" 表示 "此目錄以及所有子目錄,遞歸"。 換句話說(shuō),它啟用遞歸通配:

>>>
>>> sorted(Path('.').glob('**/*.py'))
[PosixPath('build/lib/pathlib.py'),
 PosixPath('docs/conf.py'),
 PosixPath('pathlib.py'),
 PosixPath('setup.py'),
 PosixPath('test_pathlib.py')]

備注

在一個(gè)較大的目錄樹(shù)中使用 "**" 模式可能會(huì)消耗非常多的時(shí)間。

引發(fā)一個(gè) 審計(jì)事件 pathlib.Path.glob 附帶參數(shù) self, pattern。

在 3.11 版更改: Return only directories if pattern ends with a pathname components separator (sep or altsep).

Path.group()?

返回?fù)碛写宋募挠脩艚M。如果文件的 GID 無(wú)法在系統(tǒng)數(shù)據(jù)庫(kù)中找到,將拋出 KeyError

Path.is_dir()?

如果路徑指向一個(gè)目錄(或者一個(gè)指向目錄的符號(hào)鏈接)則返回 True,如果指向其他類型的文件則返回 False。

當(dāng)路徑不存在或者是一個(gè)破損的符號(hào)鏈接時(shí)也會(huì)返回 False;其他錯(cuò)誤(例如權(quán)限錯(cuò)誤)被傳播。

Path.is_file()?

如果路徑指向一個(gè)正常的文件(或者一個(gè)指向正常文件的符號(hào)鏈接)則返回 True,如果指向其他類型的文件則返回 False

當(dāng)路徑不存在或者是一個(gè)破損的符號(hào)鏈接時(shí)也會(huì)返回 False;其他錯(cuò)誤(例如權(quán)限錯(cuò)誤)被傳播。

Path.is_mount()?

如果路徑是一個(gè) 掛載點(diǎn) <mount point>:在文件系統(tǒng)中被其他不同的文件系統(tǒng)掛載的地點(diǎn)。在 POSIX 系統(tǒng),此函數(shù)檢查 path 的父級(jí) —— path/.. 是否處于一個(gè)和 path 不同的設(shè)備中,或者 file:path/..path 是否指向相同設(shè)備的相同 i-node —— 這能檢測(cè)所有 Unix 以及 POSIX 變種上的掛載點(diǎn)。 Windows 上未實(shí)現(xiàn)。

3.7 新版功能.

如果路徑指向符號(hào)鏈接則返回 True, 否則 False。

如果路徑不存在也返回 False;其他錯(cuò)誤(例如權(quán)限錯(cuò)誤)被傳播。

Path.is_socket()?

如果路徑指向一個(gè) Unix socket 文件(或者指向 Unix socket 文件的符號(hào)鏈接)則返回 True,如果指向其他類型的文件則返回 False

當(dāng)路徑不存在或者是一個(gè)破損的符號(hào)鏈接時(shí)也會(huì)返回 False;其他錯(cuò)誤(例如權(quán)限錯(cuò)誤)被傳播。

Path.is_fifo()?

如果路徑指向一個(gè)先進(jìn)先出存儲(chǔ)(或者指向先進(jìn)先出存儲(chǔ)的符號(hào)鏈接)則返回 True ,指向其他類型的文件則返回 False。

當(dāng)路徑不存在或者是一個(gè)破損的符號(hào)鏈接時(shí)也會(huì)返回 False;其他錯(cuò)誤(例如權(quán)限錯(cuò)誤)被傳播。

Path.is_block_device()?

如果文件指向一個(gè)塊設(shè)備(或者指向塊設(shè)備的符號(hào)鏈接)則返回 True,指向其他類型的文件則返回 False。

當(dāng)路徑不存在或者是一個(gè)破損的符號(hào)鏈接時(shí)也會(huì)返回 False;其他錯(cuò)誤(例如權(quán)限錯(cuò)誤)被傳播。

Path.is_char_device()?

如果路徑指向一個(gè)字符設(shè)備(或指向字符設(shè)備的符號(hào)鏈接)則返回 True,指向其他類型的文件則返回 False。

當(dāng)路徑不存在或者是一個(gè)破損的符號(hào)鏈接時(shí)也會(huì)返回 False;其他錯(cuò)誤(例如權(quán)限錯(cuò)誤)被傳播。

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')

The children are yielded in arbitrary order, and the special entries '.' and '..' are not included. If a file is removed from or added to the directory after creating the iterator, whether a path object for that file be included is unspecified.

Path.lchmod(mode)?

就像 Path.chmod() 但是如果路徑指向符號(hào)鏈接則是修改符號(hào)鏈接的模式,而不是修改符號(hào)鏈接的目標(biāo)。

Path.lstat()?

就和 Path.stat() 一樣,但是如果路徑指向符號(hào)鏈接,則是返回符號(hào)鏈接而不是目標(biāo)的信息。

Path.mkdir(mode=0o777, parents=False, exist_ok=False)?

新建給定路徑的目錄。如果給出了 mode ,它將與當(dāng)前進(jìn)程的 umask 值合并來(lái)決定文件模式和訪問(wèn)標(biāo)志。如果路徑已經(jīng)存在,則拋出 FileExistsError。

如果 parents 為 true,任何找不到的父目錄都會(huì)伴隨著此路徑被創(chuàng)建;它們會(huì)以默認(rèn)權(quán)限被創(chuàng)建,而不考慮 mode 設(shè)置(模仿 POSIX 的 mkdir -p 命令)。

如果 parents 為 false(默認(rèn)),則找不到的父級(jí)目錄會(huì)導(dǎo)致 FileNotFoundError 被拋出。

如果 exist_ok 為 false(默認(rèn)),則在目標(biāo)已存在的情況下拋出 FileExistsError。

如果 exist_ok 為 true, 則 FileExistsError 異常將被忽略(和 POSIX mkdir -p 命令行為相同),但是只有在最后一個(gè)路徑組件不是現(xiàn)存的非目錄文件時(shí)才生效。

在 3.5 版更改: exist_ok 形參被加入。

Path.open(mode='r', buffering=- 1, encoding=None, errors=None, newline=None)?

打開(kāi)路徑指向的文件,就像內(nèi)置的 open() 函數(shù)所做的一樣:

>>>
>>> p = Path('setup.py')
>>> with p.open() as f:
...     f.readline()
...
'#!/usr/bin/env python3\n'
Path.owner()?

返回?fù)碛写宋募挠脩裘?。如果文件?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'

3.5 新版功能.

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'

文件先被打開(kāi)然后關(guān)閉。有和 open() 一樣的可選形參。

3.5 新版功能.

返回符號(hào)鏈接所指向的路徑(即 os.readlink() 的返回值):

>>>
>>> p = Path('mylink')
>>> p.symlink_to('setup.py')
>>> p.readlink()
PosixPath('setup.py')

3.9 新版功能.

Path.rename(target)?

Rename this file or directory to the given target, and return a new Path instance pointing to target. On Unix, if target exists and is a file, it will be replaced silently if the user has permission. On Windows, if target exists, FileExistsError will be raised. target can be either a string or another path object:

>>>
>>> p = Path('foo')
>>> p.open('w').write('some text')
9
>>> target = Path('bar')
>>> p.rename(target)
PosixPath('bar')
>>> target.open().read()
'some text'

目標(biāo)路徑可能為絕對(duì)或相對(duì)路徑。 相對(duì)路徑將被解釋為相對(duì)于當(dāng)前工作目錄,而 不是 相對(duì)于 Path 對(duì)象的目錄。

在 3.8 版更改: 添加了返回值,返回新的 Path 實(shí)例。

Path.replace(target)?

Rename this file or directory to the given target, and return a new Path instance pointing to target. If target points to an existing file or empty directory, it will be unconditionally replaced.

目標(biāo)路徑可能為絕對(duì)或相對(duì)路徑。 相對(duì)路徑將被解釋為相對(duì)于當(dāng)前工作目錄,而 不是 相對(duì)于 Path 對(duì)象的目錄。

在 3.8 版更改: 添加了返回值,返回新的 Path 實(shí)例。

Path.absolute()?

Make the path absolute, without normalization or resolving symlinks. Returns a new path object:

>>>
>>> p = Path('tests')
>>> p
PosixPath('tests')
>>> p.absolute()
PosixPath('/home/antoine/pathlib/tests')
Path.resolve(strict=False)?

將路徑絕對(duì)化,解析任何符號(hào)鏈接。返回新的路徑對(duì)象:

>>>
>>> p = Path()
>>> p
PosixPath('.')
>>> p.resolve()
PosixPath('/home/antoine/pathlib')

".." 組件也將被消除(只有這一種方法這么做):

>>>
>>> p = Path('docs/../setup.py')
>>> p.resolve()
PosixPath('/home/antoine/pathlib/setup.py')

如果路徑不存在并且 strict 設(shè)為 True,則拋出 FileNotFoundError。如果 strictFalse,則路徑將被盡可能地解析并且任何剩余部分都會(huì)被不檢查是否存在地追加。如果在解析路徑上發(fā)生無(wú)限循環(huán),則拋出 RuntimeError。

3.6 新版功能: 加入*strict* 參數(shù)(3.6之前的版本相當(dāng)于strict值為T(mén)rue)

Path.rglob(pattern)?

這就像調(diào)用 Path.glob`時(shí)在給定的相對(duì) *pattern* 前面添加了"``**/`()"

>>>
>>> sorted(Path().rglob("*.py"))
[PosixPath('build/lib/pathlib.py'),
 PosixPath('docs/conf.py'),
 PosixPath('pathlib.py'),
 PosixPath('setup.py'),
 PosixPath('test_pathlib.py')]

引發(fā)一個(gè) 審計(jì)事件 pathlib.Path.rglob 附帶參數(shù) self, pattern

在 3.11 版更改: Return only directories if pattern ends with a pathname components separator (sep or altsep).

Path.rmdir()?

移除此目錄。此目錄必須為空的。

Path.samefile(other_path)?

返回此目錄是否指向與可能是字符串或者另一個(gè)路徑對(duì)象的 other_path 相同的文件。語(yǔ)義類似于 os.path.samefile()os.path.samestat()

如果兩者都以同一原因無(wú)法訪問(wèn),則拋出 OSError

>>>
>>> p = Path('spam')
>>> q = Path('eggs')
>>> p.samefile(q)
False
>>> p.samefile('spam')
True

3.5 新版功能.

將此路徑創(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

備注

參數(shù)的順序(link, target) 和 os.symlink() 是相反的。

將此路徑設(shè)為一個(gè)指向與 target 相同文件的硬鏈接。

備注

參數(shù)順序 (link, target) 和 os.link() 是相反的。

3.10 新版功能.

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。

移除此文件或符號(hào)鏈接。如果路徑指向目錄,則用 Path.rmdir() 代替。

如果 missing_ok 為假值(默認(rèn)),則如果路徑不存在將會(huì)引發(fā) FileNotFoundError。

如果 missing_ok 為真值,則 FileNotFoundError 異常將被忽略(和 POSIX rm -f 命令的行為相同)。

在 3.8 版更改: 增加了 missing_ok 形參。

Path.write_bytes(data)?

將文件以二進(jìn)制模式打開(kāi),寫(xiě)入 data 并關(guān)閉:

>>>
>>> p = Path('my_binary_file')
>>> p.write_bytes(b'Binary file contents')
20
>>> p.read_bytes()
b'Binary file contents'

一個(gè)同名的現(xiàn)存文件將被覆蓋。

3.5 新版功能.

Path.write_text(data, encoding=None, errors=None, newline=None)?

將文件以文本模式打開(kāi),寫(xiě)入 data 并關(guān)閉:

>>>
>>> p = Path('my_text_file')
>>> p.write_text('Text file contents')
18
>>> p.read_text()
'Text file contents'

同名的現(xiàn)有文件會(huì)被覆蓋。 可選形參的含義與 open() 的相同。

3.5 新版功能.

在 3.10 版更改: 增加了 newline 形參。

對(duì)應(yīng)的 os 模塊的工具?

以下是一個(gè)映射了 osPurePath/Path 對(duì)應(yīng)相同的函數(shù)的表。

備注

Not all pairs of functions/methods below are equivalent. Some of them, despite having some overlapping use-cases, have different semantics. They include os.path.abspath() and Path.absolute(), os.path.relpath() and PurePath.relative_to().

osos.path

pathlib

os.path.abspath()

Path.absolute() 1

os.path.realpath()

Path.resolve()

os.chmod()

Path.chmod()

os.mkdir()

Path.mkdir()

os.makedirs()

Path.mkdir()

os.rename()

Path.rename()

os.replace()

Path.replace()

os.rmdir()

Path.rmdir()

os.remove(), os.unlink()

Path.unlink()

os.getcwd()

Path.cwd()

os.path.exists()

Path.exists()

os.path.expanduser()

Path.expanduser()Path.home()

os.listdir()

Path.iterdir()

os.path.isdir()

Path.is_dir()

os.path.isfile()

Path.is_file()

os.path.islink()

Path.is_symlink()

os.link()

Path.hardlink_to()

os.symlink()

Path.symlink_to()

os.readlink()

Path.readlink()

os.path.relpath()

Path.relative_to() 2

os.stat()

Path.stat(), Path.owner(), Path.group()

os.path.isabs()

PurePath.is_absolute()

os.path.join()

PurePath.joinpath()

os.path.basename()

PurePath.name

os.path.dirname()

PurePath.parent

os.path.samefile()

Path.samefile()

os.path.splitext()

PurePath.suffix

備注

1

os.path.abspath() normalizes the resulting path, which may change its meaning in the presence of symlinks, while Path.absolute() does not.

2

Path.relative_to() 要求 self 為參數(shù)的子路徑,但 os.path.relpath() 則不要求。