python3從零學習-5.4.1、面向對象的文件系統(tǒng)路徑pathlib

源代碼 Lib/pathlib.py

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

?? ??? ?如果你以前從未使用過此模塊或者不確定在項目中使用哪一個類是正確的,則 Path 總是你需要的。它在運行代碼的平臺上實例化為一個 具體路徑。

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

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

?? ?2.你只想操作路徑但不想實際訪問操作系統(tǒng)。在這種情況下,實例化一個純路徑是有用的,因為它們沒有任何訪問操作系統(tǒng)的操作。

參見 PEP 428:pathlib 模塊 – 面向對象的的文件系統(tǒng)路徑。

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

基礎使用

導入主類:

>>>

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

列出當前目錄樹下的所有 Python 源代碼文件:

>>>

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

[PosixPath('test_pathlib.py'), PosixPath('setup.py'),

PosixPath('pathlib.py'), PosixPath('docs/conf.py'),

PosixPath('build/lib/pathlib.py’)]

在目錄樹中移動:

>>>

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

打開一個文件:

>>>

>>> with q.open() as f: f.readline()

...

'#!/bin/bash\n'

純路徑

?? ??? ?純路徑對象提供了不實際訪問文件系統(tǒng)的路徑處理操作。有三種方式來訪問這些類,也是不同的風格:

class pathlib.PurePath(*pathsegments)

?? ??? ?一個通用的類,代表當前系統(tǒng)的路徑風格(實例化為 PurePosixPath 或者 PureWindowsPath):

>>>

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

PurePosixPath('setup.py')

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

>>>

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

PurePosixPath('foo/some/path/bar')

>>> PurePath(Path('foo'), Path('bar'))

PurePosixPath('foo/bar')

當 pathsegments 為空的時候,假定為當前目錄:

>>>

>>> PurePath()

PurePosixPath('.')

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

>>>

>>> PurePath('/etc', '/usr', 'lib64')

PurePosixPath('/usr/lib64')

>>> PureWindowsPath('c:/Windows', 'd:bar')

PureWindowsPath('d:bar')

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

>>>

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

PureWindowsPath('c:/Program Files')

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

>>>

>>> PurePath('foo//bar')

PurePosixPath('foo/bar')

>>> PurePath('foo/./bar')

PurePosixPath('foo/bar')

>>> PurePath('foo/../bar')

PurePosixPath('foo/../bar')

(如果你想讓 PurePosixPath('foo/../bar') 等同于 PurePosixPath('bar'),那么 you are too young, too simple, sometimes naive! 如果 foo 是一個指向其他其他目錄的符號鏈接,那就出毛病啦。)

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

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

class pathlib.PurePosixPath(*pathsegments)

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

>>>

>>> PurePosixPath('/etc')

PurePosixPath('/etc')

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

class pathlib.PureWindowsPath(*pathsegments)

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

>>>

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

PureWindowsPath('c:/Program Files')

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

無論你正運行什么系統(tǒng),你都可以實例化這些類,因為它們提供的操作不做任何系統(tǒng)調用。

通用性質

?? ??? ?路徑是不可變并可哈希的。相同風格的路徑可以排序與比較。這些性質尊重對應風格的大小寫轉換語義:

>>>

>>> PurePosixPath('foo') == PurePosixPath('FOO')

False

>>> PureWindowsPath('foo') == PureWindowsPath('FOO')

True

>>> PureWindowsPath('FOO') in { PureWindowsPath('foo') }

True

>>> PureWindowsPath('C:') < PureWindowsPath('d:')

True

不同風格的路徑比較得到不等的結果并且無法被排序:

>>>

>>> 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 接口實現(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'

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

>>>

>>> bytes(p)

b'/etc'

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

訪問個別部分

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

PurePath.parts

一個元組,可以訪問路徑的多個組件:

>>>

>>> p = PurePath('/usr/bin/python3')

>>> p.parts

('/', 'usr', 'bin', 'python3')

>>> p = PureWindowsPath('c:/Program Files/PSF')

>>> p.parts

('c:\\', 'Program Files', 'PSF')

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

方法和特征屬性

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

PurePath.drive

一個表示驅動器盤符或命名的字符串,如果存在:

>>>

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

'c:'

>>> PureWindowsPath('/Program Files/').drive

''

>>> PurePosixPath('/etc').drive

''

UNC 分享也被認作驅動器:

>>>

>>> PureWindowsPath('//host/share/foo.txt').drive

'\\\\host\\share'

PurePath.root

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

>>>

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

'\\'

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

''

>>> PurePosixPath('/etc').root

'/'

UNC 分享一樣擁有根:

>>>

>>> PureWindowsPath('//host/share').root

'\\'

PurePath.anchor

驅動器和根的聯(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:/')

PurePath.parent

此路徑的邏輯父路徑:

>>>

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

>>> p.parent

PurePosixPath('/a/b/c')

你不能超過一個 anchor 或空路徑:

>>>

>>> p = PurePosixPath('/')

>>> p.parent

PurePosixPath('/')

>>> p = PurePosixPath('.')

>>> p.parent

PurePosixPath('.')

注解 這是一個單純的詞法操作,因此有以下行為:

>>>

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

>>> p.parent

PurePosixPath('foo')

如果你想要向上移動任意文件系統(tǒng)路徑,推薦先使用 Path.resolve() 來解析符號鏈接以及消除 ".." 組件。

PurePath.name

一個表示最后路徑組件的字符串,排除了驅動器與根目錄,如果存在的話:

>>>

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

'setup.py'

UNC 驅動器名不被考慮:

>>>

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

'setup.py'

>>> PureWindowsPath('//some/share').name

''

PurePath.suffix

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

>>>

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

最后一個路徑組件,除去后綴:

>>>

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

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

>>>

>>> 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_reserved()

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

PureWindowsPath('nul').is_reserved()

True

PurePosixPath('nul').is_reserved()

False

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

PurePath.joinpath(*other)

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

>>>

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

將此路徑與提供的通配符風格的模式匹配。如果匹配成功則返回 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

As with other methods, case-sensitivity is observed:

>>>

>>> 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' does not start with '/usr'

PurePath.with_name(name)

返回一個新的路徑并修改 name。如果原本路徑沒有 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_suffix(suffix)

返回一個新的路徑并修改 suffix。如果原本的路徑沒有后綴,新的 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')

11.1.3. 具體路徑

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

class pathlib.Path(*pathsegments)

一個 PurePath 的子類,此類以當前系統(tǒng)的路徑風格表示路徑(實例化為 PosixPath 或 WindowsPath):

>>>

>>> Path('setup.py')

PosixPath('setup.py')

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

class pathlib.PosixPath(*pathsegments)

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

>>>

>>> PosixPath('/etc')

PosixPath('/etc')

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

class pathlib.WindowsPath(*pathsegments)

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

>>>

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

WindowsPath('c:/Program Files')

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

你只能實例化與當前系統(tǒng)風格相同的類(允許系統(tǒ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

11.1.3.1. 方法

除純路徑方法外,具體路徑還提供以下方法。如果系統(tǒng)調用失?。ɡ缫驗槁窂讲淮嬖冢?,其中許多方法都會引發(fā) OSError:

classmethod Path.cwd()

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

>>>

>>> Path.cwd()

PosixPath('/home/antoine/pathlib')

classmethod Path.home()

返回一個表示當前用戶家目錄的新路徑對象(和 os.path.expanduser() 構造含 ~ 路徑返回的相同):

>>>

>>> Path.home()

PosixPath('/home/antoine')

3.5 新版功能.

Path.stat()

Return information about this path (similarly to os.stat()). The result is looked up at each call to this method.

p = Path('setup.py')

p.stat().st_size

956

p.stat().st_mtime

1327883547.852554

Path.chmod(mode)

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

>>>

>>> p = Path('setup.py')

>>> p.stat().st_mode

33277

>>> p.chmod(0o444)

>>> p.stat().st_mode

33060

Path.exists()

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

>>>

>>> Path('.').exists()

True

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

True

>>> Path('/etc').exists()

True

>>> Path('nonexistentfile').exists()

False

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

Path.expanduser()

返回展開了包含 ~ 和 ~user 的構造,就和 os.path.expanduser() 一樣:

>>>

>>> p = PosixPath('~/films/Monty Python')

>>> p.expanduser()

PosixPath('/home/eric/films/Monty Python')

3.5 新版功能.

Path.glob(pattern)

Glob the given pattern in the directory represented by this path, yielding all matching files (of any kind):

>>>

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

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

Path.is_dir()

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

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

Path.is_file()

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

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

Path.is_symlink()

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

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

Path.is_socket()

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

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

Path.is_fifo()

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

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

Path.is_block_device()

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

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

Path.is_char_device()

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

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

Path.iterdir()

當路徑指向一個目錄時,產生該路徑下的對象的路徑:

>>>

>>> 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.lchmod(mode)

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

Path.lstat()

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

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

新建給定路徑的目錄。如果給出了 mode ,它將與當前進程的 umask 值合并來決定文件模式和訪問標志。如果路徑已經存在,則拋出 FileExistsError。

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

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

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

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

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

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

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

>>>

>>> p = Path('setup.py')

>>> with p.open() as f:

...?????f.readline()

...

'#!/usr/bin/env python3\n'

Path.owner()

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

Path.read_bytes()

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

>>>

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

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

3.5 新版功能.

Path.rename(target)

使用給定的 target 將文件重命名。在 Unix 上,如果 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 重命名文件或目錄。如果 target 指向現(xiàn)存的文件或目錄,則將被無條件覆蓋。

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。如果 strict 為 False,則路徑將被盡可能地解析并且任何剩余部分都會被不檢查是否存在地追加。如果在解析路徑上發(fā)生無限循環(huán),則拋出 RuntimeError。

3.6 新版功能: The strict argument.

Path.rglob(pattern)

This is like calling Path.glob() with “**” added in front of the given pattern:

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)

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

如果兩者都以同一原因無法訪問,則拋出 OSError。

p = Path('spam')

q = Path('eggs')

p.samefile(q)

False

p.samefile('spam')

True

3.5 新版功能.

Path.symlink_to(target, target_is_directory=False)

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

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

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

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

Path.unlink()

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

Path.write_bytes(data)

將文件以二進制模式打開,寫入 data 并關閉:

>>>

>>> p = Path('my_binary_file')

>>> p.write_bytes(b'Binary file contents')

20

>>> p.read_bytes()

b'Binary file contents'

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

3.5 新版功能.

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

將文件以文本模式打開,寫入 data 并關閉:

>>>

>>> p = Path('my_text_file')

>>> p.write_text('Text file contents')

18

>>> p.read_text()

'Text file contents'

3.5 新版功能.

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容