pathlib --- 面向對象的文件系統路徑?

3.4 新版功能.

源代碼 Lib/pathlib.py


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

../images/pathlib-inheritance.png

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

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

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

  2. 你只想操作路徑但不想實(shí)際訪(fǎng)問(wèn)操作系統。在這種情況下,實(shí)例化一個(gè)純路徑是有用的,因為它們沒(méi)有任何訪(fǎng)問(wèn)操作系統的操作。

參見(jiàn)

PEP 428:pathlib 模塊 -- 面向對象的的文件系統路徑。

參見(jiàn)

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

基礎使用?

導入主類(lèi):

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

列出當前目錄樹(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')

查詢(xún)路徑的屬性:

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

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

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

純路徑?

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

class pathlib.PurePath(*pathsegments)?

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

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

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

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

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

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

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

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

但是,在 Windows 路徑中,改變本地根目錄并不會(huì )丟棄之前盤(pán)符的設置:

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

假斜線(xiàn)和單獨的點(diǎn)都會(huì )被消除,但是雙點(diǎn) (‘..’) 不會(huì ),以防改變符號鏈接的含義。

>>>
>>> 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è)指向其他目錄的符號鏈接那么這個(gè)做法就將出錯)

純路徑對象實(shí)現了 os.PathLike 接口,允許它們在任何接受此接口的地方使用。

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

class pathlib.PurePosixPath(*pathsegments)?

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

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

pathsegments 參數的指定和 PurePath 相同。

class pathlib.PureWindowsPath(*pathsegments)?

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

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

pathsegments 參數的指定和 PurePath 相同。

無(wú)論你正運行什么系統,你都可以實(shí)例化這些類(lèi),因為它們提供的操作不做任何系統調用。

通用性質(zhì)?

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

>>>
>>> PurePosixPath('foo') == PurePosixPath('FOO')
False
>>> PureWindowsPath('foo') == PureWindowsPath('FOO')
True
>>> PureWindowsPath('FOO') in { PureWindowsPath('foo') }
True
>>> PureWindowsPath('C:') < PureWindowsPath('d:')
True

不同風(fēng)格的路徑比較得到不等的結果并且無(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'

運算符?

斜杠 / 操作符有助于創(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')

文件對象可用于任何接受 os.PathLike 接口實(shí)現的地方。

>>>
>>> import os
>>> p = PurePath('/etc')
>>> os.fspath(p)
'/etc'

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

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

類(lèi)似地,在路徑上調用 bytes 將原始文件系統路徑作為字節對象給出,就像被 os.fsencode() 編碼一樣:

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

備注

只推薦在 Unix 下調用 bytes。在 Windows, unicode 形式是文件系統路徑的規范表示法。

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

為了訪(fǎng)問(wèn)路徑獨立的部分 (組件),使用以下特征屬性:

PurePath.parts?

一個(gè)元組,可以訪(fǎng)問(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è)表示驅動(dòng)器盤(pán)符或命名的字符串,如果存在:

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

UNC 分享也被認作驅動(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?

驅動(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 序列現在支持 切片 負的索引值。

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)任意文件系統路徑,推薦先使用 Path.resolve() 來(lái)解析符號鏈接以及消除 ".." 組件。

PurePath.name?

一個(gè)表示最后路徑組件的字符串,排除了驅動(dòng)器與根目錄,如果存在的話(huà):

>>>
>>> PurePosixPath('my/library/setup.py').name
'setup.py'

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

>>>
>>> PureWindowsPath('//some/share/setup.py').name
'setup.py'
>>> PureWindowsPath('//some/share').name
''
PurePath.suffix?

最后一個(gè)組件的文件擴展名,如果存在:

>>>
>>> PurePosixPath('my/library/setup.py').suffix
'.py'
>>> PurePosixPath('my/library.tar.gz').suffix
'.gz'
>>> PurePosixPath('my/library').suffix
''
PurePath.suffixes?

路徑的文件擴展名列表:

>>>
>>> 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。如果并非絕對路徑,拋出 ValueError。

>>>
>>> p = PurePosixPath('/etc/passwd')
>>> p.as_uri()
'file:///etc/passwd'
>>> p = PureWindowsPath('c:/Windows')
>>> p.as_uri()
'file:///c:/Windows'
PurePath.is_absolute()?

返回此路徑是否為絕對路徑。如果路徑同時(shí)擁有驅動(dòng)器符與根路徑(如果風(fēng)格允許)則將被認作絕對路徑。

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

返回此路徑是否相對于 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

當保留路徑上的文件系統被調用,則可能出現玄學(xué)失敗或者意料之外的效應。

PurePath.joinpath(*other)?

調用此方法等同于將每個(gè) other 參數中的項目連接在一起:

>>>
>>> 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 是相對的,則路徑可以是相對路徑或絕對路徑,并且匹配是從右側完成的:

>>>
>>> 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 是絕對的,則路徑必須是絕對的,并且路徑必須完全匹配:

>>>
>>> PurePath('/a.py').match('/*.py')
True
>>> PurePath('a/b.py').match('/*.py')
False

與其他方法一樣,是否大小寫(xiě)敏感遵循平臺的默認規則:

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

計算此路徑相對 other 表示路徑的版本。如果不可計算,則拋出 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.

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

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)]有名稱(chē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')

具體路徑?

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

class pathlib.Path(*pathsegments)?

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

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

pathsegments 參數的指定和 PurePath 相同。

class pathlib.PosixPath(*pathsegments)?

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

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

pathsegments 參數的指定和 PurePath 相同。

class pathlib.WindowsPath(*pathsegments)?

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

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

pathsegments 參數的指定和 PurePath 相同。

你只能實(shí)例化與當前系統風(fēng)格相同的類(lèi)(允許系統調用作用于不兼容的路徑風(fēng)格可能在應用程序中導致缺陷或失?。?

>>>
>>> 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í)體路徑還提供以下方法。 如果系統調用失?。ɡ缫驗槁窂讲淮嬖冢┻@些方法中許多都會(huì )引發(fā) OSError。

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

classmethod Path.cwd()?

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

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

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

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

3.5 新版功能.

Path.stat(*, follow_symlinks=True)?

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

此方法通常會(huì )跟隨符號鏈接;要對 symlink 使用 stat 請添加參數 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)?

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

此方法通常會(huì )跟隨符號鏈接。 某些 Unix 變種支持改變 symlink 本身的權限;在這些平臺上你可以添加參數 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è)符號鏈接, exists() 返回此符號鏈接是否指向存在的文件或目錄。

Path.expanduser()?

返回帶有擴展 ~~user 構造的新路徑,與 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)?

解析相對于此路徑的通配符 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 的相同,還增加了 "**" 表示 "此目錄以及所有子目錄,遞歸"。 換句話(huà)說(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è) 審計事件 pathlib.Path.glob 附帶參數 self, pattern。

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

Path.group()?

返回擁有此文件的用戶(hù)組。如果文件的 GID 無(wú)法在系統數據庫中找到,將拋出 KeyError 。

Path.is_dir()?

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

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

Path.is_file()?

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

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

Path.is_mount()?

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

3.7 新版功能.

如果路徑指向符號鏈接則返回 True, 否則 False。

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

Path.is_socket()?

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

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

Path.is_fifo()?

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

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

Path.is_block_device()?

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

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

Path.is_char_device()?

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

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

Path.iterdir()?

當路徑指向一個(gè)目錄時(shí),產(chǎn)生該路徑下的對象的路徑:

>>>
>>> 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() 但是如果路徑指向符號鏈接則是修改符號鏈接的模式,而不是修改符號鏈接的目標。

Path.lstat()?

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

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

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

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

如果 parents 為 false(默認),則找不到的父級目錄會(huì )導致 FileNotFoundError 被拋出。

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

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

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

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

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

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

返回擁有此文件的用戶(hù)名。如果文件的 UID 無(wú)法在系統數據庫中找到,則拋出 KeyError。

Path.read_bytes()?

以字節對象的形式返回路徑指向的文件的二進(jìn)制內容:

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

以字符串形式返回路徑指向的文件的解碼后文本內容。

>>>
>>> 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 新版功能.

返回符號鏈接所指向的路徑(即 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'

目標路徑可能為絕對或相對路徑。 相對路徑將被解釋為相對于當前工作目錄,而 不是 相對于 Path 對象的目錄。

在 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.

目標路徑可能為絕對或相對路徑。 相對路徑將被解釋為相對于當前工作目錄,而 不是 相對于 Path 對象的目錄。

在 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)?

將路徑絕對化,解析任何符號鏈接。返回新的路徑對象:

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

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

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

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

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

Path.rglob(pattern)?

這就像調用 Path.glob`時(shí)在給定的相對 *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è) 審計事件 pathlib.Path.rglob 附帶參數 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è)路徑對象的 other_path 相同的文件。語(yǔ)義類(lèi)似于 os.path.samefile()os.path.samestat()。

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

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

3.5 新版功能.

將此路徑創(chuàng )建為指向 target 的符號鏈接。在 Windows 下,如果鏈接的目標是一個(gè)目錄則 target_is_directory 必須為 true (默認為 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

備注

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

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

備注

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

3.10 新版功能.

Path.touch(mode=0o666, exist_ok=True)?

將給定的路徑創(chuàng )建為文件。如果給出了 mode 它將與當前進(jìn)程的 umask 值合并以確定文件的模式和訪(fǎng)問(wèn)標志。如果文件已經(jīng)存在,則當 exist_ok 為 true 則函數仍會(huì )成功(并且將它的修改事件更新為當前事件),否則拋出 FileExistsError。

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

如果 missing_ok 為假值(默認),則如果路徑不存在將會(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è)同名的現存文件將被覆蓋。

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'

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

3.5 新版功能.

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

對應的 os 模塊的工具?

以下是一個(gè)映射了 osPurePath/Path 對應相同的函數的表。

備注

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 為參數的子路徑,但 os.path.relpath() 則不要求。