pathlib
--- オブジェクト指向のファイルシステムパス¶
Added in version 3.4.
ソースコード: Lib/pathlib/
このモジュールはファイルシステムのパスを表すクラスを提供していて、様々なオペレーティングシステムについての適切な意味論をそれらのクラスに持たせています。 Path クラスは 純粋パス と 具象パス からなります。 純粋パスは I/O を伴わない純粋な計算操作を提供します。 具象パスは純粋パスを継承していますが、 I/O 操作も提供しています。
![../_images/pathlib-inheritance.png](../_images/pathlib-inheritance.png)
あなたが今までこのモジュールを使用したことがない場合や、タスクに適しているのがどのクラスかわからない場合は、 Path
はきっとあなたに必要なものでしょう。
Path
はコードが実行されているプラットフォーム用の 具象パス のインスタンスを作成します。
純粋パスは、以下のようないくつかの特殊なケースで有用です:
Unix マシン上で Windows のパスを扱いたいとき (またはその逆)。Unix 上で実行しているときに
WindowsPath
のインスタンスを作成することはできませんが、PureWindowsPath
なら可能になります。実際に OS にアクセスすることなしにパスを操作するだけのコードを確認したいとき。この場合、純粋クラスのインスタンスを一つ作成すれば、それが OS にアクセスすることはないので便利です。
参考
PEP 428: The pathlib module -- オブジェクト指向のファイルシステムパス。
参考
文字列による低水準のパス操作の場合は 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'
例外¶
- exception pathlib.UnsupportedOperation¶
An exception inheriting
NotImplementedError
that is raised when an unsupported operation is called on a path object.Added in version 3.13.
純粋パス¶
純粋パスオブジェクトは実際にファイルシステムにアクセスしないパス操作処理を提供します。これらのクラスにアクセスするには 3 つの方法があり、それらを フレーバー と呼んでいます:
- class pathlib.PurePath(*pathsegments)¶
システムのパスのフレーバーを表すジェネリッククラスです (インスタンスを作成することで
PurePosixPath
またはPureWindowsPath
のどちらかが作成されます):>>> PurePath('setup.py') # Running on a Unix machine PurePosixPath('setup.py')
pathsegments の各要素は、パスの構成要素を表す文字列か、パスオブジェクトなどの、
os.PathLike
インターフェースを実装するオブジェクトである必要があります。os.PathLike
インターフェースでは、__fspath__()
メソッドが文字列を返します:>>> 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の場合、ルート相対パス (例えば
r'\foo'
) があってもドライブ名はそのまま変わりません:>>> PureWindowsPath('c:/Windows', '/Program Files') PureWindowsPath('c:/Program Files')
単一スラッシュと等価な複数スラッシュやシングルドットは簡略化されますが、ダブルドット (
'..'
) や先頭に位置するダブルスラッシュ ('//'
) は簡略化されません。 これは、様々な理由でパスの意味が簡略化した場合と異なってしまうからです (例: シンボリックリンク、UNCパス):>>> PurePath('foo//bar') PurePosixPath('foo/bar') >>> PurePath('//foo/bar') PurePosixPath('//foo/bar') >>> PurePath('foo/./bar') PurePosixPath('foo/bar') >>> PurePath('foo/../bar') PurePosixPath('foo/../bar')
(通常
PurePosixPath('foo/../bar')
はPurePosixPath('bar')
と等価になりますが、foo
が他のディレクトリへのシンボリックリンクの場合は等価になりません)純粋パスオブジェクトは
os.PathLike
インターフェースを実装しており、そのインターフェースを受理する箇所ならどこでも使用することができます。バージョン 3.6 で変更:
os.PathLike
インターフェースがサポートされました。
- class pathlib.PurePosixPath(*pathsegments)¶
PurePath
のサブクラスです。このパスフレーバーは非 Windows パスを表します:>>> PurePosixPath('/etc') PurePosixPath('/etc')
pathsegments の指定は
PurePath
と同じです。
- class pathlib.PureWindowsPath(*pathsegments)¶
PurePath
のサブクラスです。このパスフレーバー UNC paths を含む Windows ファイルシステムパスを表します:>>> PureWindowsPath('c:/Program Files/') PureWindowsPath('c:/Program Files') >>> PureWindowsPath('//server/share/file') PureWindowsPath('//server/share/file')
pathsegments の指定は
PurePath
と同じです。
これらクラスはあらゆるシステムコールを行わないため、起動しているシステムにかかわらずインスタンスを作成できます。
全般的な性質¶
パスオブジェクトはイミュータブルで :term:`ハッシュ可能 <hashable>`です。 同じフレーバーのパスオブジェクトは比較ならびに順序付け可能です。 これらのプロパティは、フレーバーのケースフォールディング (訳注: 比較のために正規化すること、例えば全て大文字にする) のセマンティクスに従います。
>>> 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'
演算子¶
スラッシュ演算子を使って、 os.path.join()
のように子パスを作成することができます。
スラッシュの右側が絶対パスである場合、左側のパスは無視されます。
Windows環境で、右側のパスがルート相対パス (例: r'\foo'
) である場合、ドライブ名はリセットされません:
>>> p = PurePath('/etc')
>>> p
PurePosixPath('/etc')
>>> p / 'init.d' / 'apache2'
PurePosixPath('/etc/init.d/apache2')
>>> q = PurePath('bin')
>>> '/usr' / q
PurePosixPath('/usr/bin')
>>> p / '/an_absolute_path'
PurePosixPath('/an_absolute_path')
>>> PureWindowsPath('c:/Windows', '/Program Files')
PureWindowsPath('c:/Program Files')
os.PathLike
を実装したオブジェクトが受理できる箇所ならどこでも、パスオブジェクトが使用できます:
>>> import os
>>> p = PurePath('/etc')
>>> os.fspath(p)
'/etc'
パスオブジェクトの文字列表現はそのシステム自身の Raw ファイルシステムパス (ネイティブの形式、例えば Windows では区切り文字がバックスラッシュ) になり、文字列としてファイルパスを取るあらゆる関数に渡すことができます:
>>> p = PurePath('/etc')
>>> str(p)
'/etc'
>>> p = PureWindowsPath('c:/Program Files')
>>> str(p)
'c:\\Program Files'
同様に、パスオブジェクトを bytes
で呼び出すと、Raw ファイルシステムパスを os.fsencode()
でエンコードされたバイト列オブジェクトで返します:
>>> bytes(p)
b'/etc'
注釈
bytes
での呼び出しは Unix 上での使用のみ推奨します。Windows では Unicode 形式が標準的なファイルシステムパス表現になります。
個別の構成要素へのアクセス¶
パスの個別の "構成要素" へアクセスするには、以下のプロパティを使用します:
- 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.parser¶
The implementation of the
os.path
module used for low-level path parsing and joining: eitherposixpath
orntpath
.Added in version 3.13.
- 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 '\\'
PurePosixPath
でパスの先頭が3つ以上の連続したスラッシュである場合、 余分なスラッシュは除去されます:>>> PurePosixPath('//etc').root '//' >>> PurePosixPath('///etc').root '/' >>> PurePosixPath('////etc').root '/'
注釈
この挙動は、以下に示す、 The Open Group Base Specifications Issue 6 の 4.11 Pathname Resolution に沿ったものです:
"A pathname that begins with two successive slashes may be interpreted in an implementation-defined manner, although more than two leading slashes shall be treated as a single slash."
- PurePath.anchor¶
ドライブとルートを結合した文字列になります:
>>> PureWindowsPath('c:/Program Files/').anchor 'c:\\' >>> PureWindowsPath('c:Program Files/').anchor 'c:' >>> PurePosixPath('/etc').anchor '/' >>> PureWindowsPath('//host/share').anchor '\\\\host\\share\\'
- PurePath.parents¶
パスの論理的な上位パスにアクセスできるイミュータブルなシーケンスになります:
>>> 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')
アンカーの位置を超えることや空のパスになる位置には対応していません:
>>> p = PurePosixPath('/') >>> p.parent PurePosixPath('/') >>> p = PurePosixPath('.') >>> p.parent PurePosixPath('.')
注釈
これは純粋な字句操作であるため、以下のような挙動になります:
>>> p = PurePosixPath('foo/..') >>> p.parent PurePosixPath('foo')
任意のファイルシステムパスを上位方向に移動したい場合、シンボリックリンクの解決や
".."
要素の除去のため、最初に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¶
The last dot-separated portion of the final component, if any:
>>> PurePosixPath('my/library/setup.py').suffix '.py' >>> PurePosixPath('my/library.tar.gz').suffix '.gz' >>> PurePosixPath('my/library').suffix ''
This is commonly called the file extension.
バージョン 3.14 で変更: A single dot ("
.
") is considered a valid suffix.
- PurePath.suffixes¶
A list of the path's suffixes, often called file extensions:
>>> PurePosixPath('my/library.tar.gar').suffixes ['.tar', '.gar'] >>> PurePosixPath('my/library.tar.gz').suffixes ['.tar', '.gz'] >>> PurePosixPath('my/library').suffixes []
バージョン 3.14 で変更: A single dot ("
.
") is considered a valid suffix.
- 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.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_relative_to(other)¶
このパスが other パスに対して相対なのかそうでないのかの結果を返します。
>>> p = PurePath('/etc/passwd') >>> p.is_relative_to('/etc') True >>> p.is_relative_to('/usr') False
This method is string-based; it neither accesses the filesystem nor treats "
..
" segments specially. The following code is equivalent:>>> u = PurePath('/usr') >>> u == p or u in p.parents False
Added in version 3.9.
バージョン 3.12 で非推奨、バージョン 3.14 で削除: 追加の引数指定は非推奨となりました。指定された場合は other と連結されます。
- PurePath.is_reserved()¶
PureWindowsPath
の場合はパスが Windows 上で予約されていればTrue
を返し、そうでなければFalse
を返します。PurePosixPath
の場合は常にFalse
を返します。バージョン 3.13 で変更: Windows path names that contain a colon, or end with a dot or a space, are considered reserved. UNC paths may be reserved.
バージョン 3.13 で非推奨、バージョン 3.15 で削除予定: This method is deprecated; use
os.path.isreserved()
to detect reserved paths on Windows.
- PurePath.joinpath(*pathsegments)¶
このメソッドの呼び出しは、与えられた pathsegments のパスを順番に結合することと等価です。
>>> 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.full_match(pattern, *, case_sensitive=None)¶
Match this path against the provided glob-style pattern. Return
True
if matching is successful,False
otherwise. For example:>>> PurePath('a/b.py').full_match('a/*.py') True >>> PurePath('a/b.py').full_match('*.py') False >>> PurePath('/a/b/c.py').full_match('/a/**') True >>> PurePath('/a/b/c.py').full_match('**/*.py') True
参考
Pattern language documentation.
他のメソッドと同様に、大文字小文字の区別はプラットフォームの設定に従います:
>>> PurePosixPath('b.py').full_match('*.PY') False >>> PureWindowsPath('b.py').full_match('*.PY') True
Set case_sensitive to
True
orFalse
to override this behaviour.Added in version 3.13.
- PurePath.match(pattern, *, case_sensitive=None)¶
Match this path against the provided non-recursive glob-style pattern. Return
True
if matching is successful,False
otherwise.This method is similar to
full_match()
, but empty patterns aren't allowed (ValueError
is raised), the recursive wildcard "**
" isn't supported (it acts like non-recursive "*
"), and if a relative pattern is provided, then matching is done from the right:>>> 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
バージョン 3.12 で変更: The pattern parameter accepts a path-like object.
バージョン 3.12 で変更: case_sensitive 引数が追加されました。
- PurePath.relative_to(other, walk_up=False)¶
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 941, in relative_to raise ValueError(error_message.format(str(self), str(formatted))) ValueError: '/etc/passwd' is not in the subpath of '/usr' OR one path is relative and the other is absolute.
When walk_up is false (the default), the path must start with other. When the argument is true,
..
entries may be added to form the relative path. In all other cases, such as the paths referencing different drives,ValueError
is raised.:>>> p.relative_to('/usr', walk_up=True) PurePosixPath('../etc/passwd') >>> p.relative_to('foo', walk_up=True) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "pathlib.py", line 941, in relative_to raise ValueError(error_message.format(str(self), str(formatted))) ValueError: '/etc/passwd' is not on the same drive as 'foo' OR one path is relative and the other is absolute.
警告
This function is part of
PurePath
and works with strings. It does not check or access the underlying file structure. This can impact the walk_up option as it assumes that no symlinks are present in the path; callresolve()
first if necessary to resolve symlinks.バージョン 3.12 で変更: walk_up 引数が追加されました(
walk_up=False
を指定すると以前の動作と同じになります)。バージョン 3.12 で非推奨、バージョン 3.14 で削除: 追加の位置引数の指定は非推奨となりました。指定された場合は other と連結されます。
- 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_stem(stem)¶
現在のパスの
stem
部分を変更したパスを返します。オリジナルパスにstem
部分がない場合は 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
Added in version 3.9.
- PurePath.with_suffix(suffix)¶
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')
バージョン 3.14 で変更: A single dot ("
.
") is considered a valid suffix. In previous versions,ValueError
is raised if a single dot is supplied.
- PurePath.with_segments(*pathsegments)¶
Create a new path object of the same type by combining the given pathsegments. This method is called whenever a derivative path is created, such as from
parent
andrelative_to()
. Subclasses may override this method to pass information to derivative paths, for example:from pathlib import PurePosixPath class MyPath(PurePosixPath): def __init__(self, *pathsegments, session_id): super().__init__(*pathsegments) self.session_id = session_id def with_segments(self, *pathsegments): return type(self)(*pathsegments, session_id=self.session_id) etc = MyPath('/etc', session_id=42) hosts = etc / 'hosts' print(hosts.session_id) # 42
Added in version 3.12.
具象パス¶
具象パスは純粋パスクラスのサブクラスです。純粋パスが提供する操作に加え、パスオブジェクト上でシステムコールを呼ぶメソッドも提供しています。具象パスのインスタンスを作成するには 3 つの方法があります:
- class pathlib.Path(*pathsegments)¶
PurePath
のサブクラスであり、システムのパスフレーバーの具象パスを表します (このインスタンスの作成でPosixPath
かWindowsPath
のどちらかが作成されます):>>> Path('setup.py') PosixPath('setup.py')
pathsegments の指定は
PurePath
と同じです。
- class pathlib.PosixPath(*pathsegments)¶
Path
およびPurePosixPath
のサブクラスで、非 Windows ファイルシステムの具象パスを表します:>>> PosixPath('/etc') PosixPath('/etc')
pathsegments の指定は
PurePath
と同じです。バージョン 3.13 で変更: Raises
UnsupportedOperation
on Windows. In previous versions,NotImplementedError
was raised instead.
- class pathlib.WindowsPath(*pathsegments)¶
Path
およびPureWindowsPath
のサブクラスで、Windows ファイルシステムの具象パスを表します:>>> WindowsPath('c:/Program Files/') WindowsPath('c:/Program Files')
pathsegments の指定は
PurePath
と同じです。バージョン 3.13 で変更: Raises
UnsupportedOperation
on non-Windows platforms. In previous versions,NotImplementedError
was raised instead.
インスタンスを作成できるのはシステムと一致するフレーバーのみです (互換性のないパスフレーバーでのシステムコールの許可はバグやアプリケーションの異常終了の原因になります):
>>> 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__,))
UnsupportedOperation: cannot instantiate 'WindowsPath' on your system
Some concrete path methods can raise an OSError
if a system call fails
(for example because the path doesn't exist).
Parsing and generating URIs¶
Concrete path objects can be created from, and represented as, 'file' URIs conforming to RFC 8089.
注釈
File URIs are not portable across machines with different filesystem encodings.
- classmethod Path.from_uri(uri)¶
Return a new path object from parsing a 'file' URI. For example:
>>> p = Path.from_uri('file:///etc/hosts') PosixPath('/etc/hosts')
On Windows, DOS device and UNC paths may be parsed from URIs:
>>> p = Path.from_uri('file:///c:/windows') WindowsPath('c:/windows') >>> p = Path.from_uri('file://server/share') WindowsPath('//server/share')
Several variant forms are supported:
>>> p = Path.from_uri('file:////server/share') WindowsPath('//server/share') >>> p = Path.from_uri('file://///server/share') WindowsPath('//server/share') >>> p = Path.from_uri('file:c:/windows') WindowsPath('c:/windows') >>> p = Path.from_uri('file:/c|/windows') WindowsPath('c:/windows')
ValueError
is raised if the URI does not start withfile:
, or the parsed path isn't absolute.Added in version 3.13.
- Path.as_uri()¶
Represent the path as a 'file' URI.
ValueError
is raised if the path isn't absolute.>>> p = PosixPath('/etc/passwd') >>> p.as_uri() 'file:///etc/passwd' >>> p = WindowsPath('c:/Windows') >>> p.as_uri() 'file:///c:/Windows'
For historical reasons, this method is also available from
PurePath
objects. However, its use ofos.fsencode()
makes it strictly impure.
Querying file type and status¶
バージョン 3.8 で変更: exists()
, is_dir()
, is_file()
, is_mount()
, is_symlink()
, is_block_device()
, is_char_device()
, is_fifo()
, is_socket()
は、OSレベルで表現不能な文字を含むパスに対して、例外を送出する代わりに False
を返すようになりました。
バージョン 3.14 で変更: The methods given above now return False
instead of raising any
OSError
exception from the operating system. In previous versions,
some kinds of OSError
exception are raised, and others suppressed.
The new behaviour is consistent with os.path.exists()
,
os.path.isdir()
, etc. Use stat()
to retrieve the file
status without suppressing exceptions.
- Path.stat(*, follow_symlinks=True)¶
(
os.stat()
と同様の) 現在のパスについてos.stat_result
オブジェクトが含む情報を返します。値はそれぞれのメソッドを呼び出した時点のものになります。このメソッドは通常はシンボリックリンクをたどります。シンボリックリンクに対して 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.lstat()¶
Path.stat()
のように振る舞いますが、パスがシンボリックリンクを指していた場合、リンク先ではなくシンボリックリンク自身の情報を返します。
- Path.exists(*, follow_symlinks=True)¶
Return
True
if the path points to an existing file or directory.False
will be returned if the path is invalid, inaccessible or missing. UsePath.stat()
to distinguish between these cases.このメソッドは通常はシンボリックリンクをたどります。シンボリックリンクが存在するかを確認したい場合は
follow_symlinks=False
引数を追加してください。>>> Path('.').exists() True >>> Path('setup.py').exists() True >>> Path('/etc').exists() True >>> Path('nonexistentfile').exists() False
バージョン 3.12 で変更: follow_symlinks パラメータが追加されました。
- Path.is_file(*, follow_symlinks=True)¶
Return
True
if the path points to a regular file.False
will be returned if the path is invalid, inaccessible or missing, or if it points to something other than a regular file. UsePath.stat()
to distinguish between these cases.This method normally follows symlinks; to exclude symlinks, add the argument
follow_symlinks=False
.バージョン 3.13 で変更: follow_symlinks パラメータが追加されました。
- Path.is_dir(*, follow_symlinks=True)¶
Return
True
if the path points to a directory.False
will be returned if the path is invalid, inaccessible or missing, or if it points to something other than a directory. UsePath.stat()
to distinguish between these cases.This method normally follows symlinks; to exclude symlinks to directories, add the argument
follow_symlinks=False
.バージョン 3.13 で変更: follow_symlinks パラメータが追加されました。
- Path.is_symlink()¶
Return
True
if the path points to a symbolic link, even if that symlink is broken.False
will be returned if the path is invalid, inaccessible or missing, or if it points to something other than a symbolic link. UsePath.stat()
to distinguish between these cases.
- Path.is_junction()¶
パスがジャンクションを指している場合は
True
を返し、それ以外の場合はFalse
を返します。現在はWindowsのみジャンクションをサポートしています。Added in version 3.12.
- Path.is_mount()¶
パスがマウントポイント mount point (ファイルシステムの中で異なるファイルシステムがマウントされているところ) なら、
True
を返します。POSIX では、この関数は path の親ディレクトリであるpath/..
が path と異なるデバイス上にあるか、あるいはpath/..
と path が同じデバイス上の同じ i-node を指しているかをチェックします --- これによって全ての Unix 系システムと POSIX 標準でマウントポイントが検出できます。Windowsでは、マウントポイントはドライブレターを持つルート(e.g.c:\
)、共有 UNC(e.g.\\server\share
)またはマウントされたファイルシステムのディレクトリです。Added in version 3.7.
バージョン 3.12 で変更: Windows のサポートが追加されました。
- Path.is_socket()¶
Return
True
if the path points to a Unix socket.False
will be returned if the path is invalid, inaccessible or missing, or if it points to something other than a Unix socket. UsePath.stat()
to distinguish between these cases.
- Path.is_fifo()¶
Return
True
if the path points to a FIFO.False
will be returned if the path is invalid, inaccessible or missing, or if it points to something other than a FIFO. UsePath.stat()
to distinguish between these cases.
- Path.is_block_device()¶
Return
True
if the path points to a block device.False
will be returned if the path is invalid, inaccessible or missing, or if it points to something other than a block device. UsePath.stat()
to distinguish between these cases.
- Path.is_char_device()¶
Return
True
if the path points to a character device.False
will be returned if the path is invalid, inaccessible or missing, or if it points to something other than a character device. UsePath.stat()
to distinguish between these cases.
- Path.samefile(other_path)¶
このパスが参照するファイルが other_path (Path オブジェクトか文字列) と同じであれば
True
を、異なるファイルであればFalse
を返します。意味的にはos.path.samefile()
およびos.path.samestat()
と同じです。なんらかの理由でどちらかのファイルにアクセスできない場合は
OSError
が送出されます。>>> p = Path('spam') >>> q = Path('eggs') >>> p.samefile(q) False >>> p.samefile('spam') True
Added in version 3.5.
Reading and writing files¶
- Path.open(mode='r', buffering=-1, encoding=None, errors=None, newline=None)¶
組み込み関数
open()
のようにパスが指しているファイルを開きます:>>> p = Path('setup.py') >>> with p.open() as f: ... f.readline() ... '#!/usr/bin/env python3\n'
- Path.read_text(encoding=None, errors=None, newline=None)¶
指定されたファイルの内容を文字列としてデコードして返します:
>>> p = Path('my_text_file') >>> p.write_text('Text file contents') 18 >>> p.read_text() 'Text file contents'
ファイルを開いた後に閉じます。 オプションのパラメーターの意味は
open()
と同じです。Added in version 3.5.
バージョン 3.13 で変更: newline パラメータが追加されました。
- Path.read_bytes()¶
指定されたファイルの内容をバイナリオブジェクトで返します:
>>> p = Path('my_binary_file') >>> p.write_bytes(b'Binary file contents') 20 >>> p.read_bytes() b'Binary file contents'
Added in version 3.5.
- Path.write_text(data, encoding=None, errors=None, newline=None)¶
指定されたファイルをテキストモードで開き、data を書き込み、ファイルを閉じます:
>>> p = Path('my_text_file') >>> p.write_text('Text file contents') 18 >>> p.read_text() 'Text file contents'
同じ名前のファイルが存在する場合は上書きされます。オプションのパラメーターの意味は
open()
と同じです。Added in version 3.5.
バージョン 3.10 で変更: newline パラメータが追加されました。
- 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'
同じ名前のファイルがすでにあれば上書きされます。
Added in version 3.5.
Reading directories¶
- Path.iterdir()¶
パスがディレクトリを指していた場合、ディレクトリの内容のパスオブジェクトを yield します:
>>> 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, it is unspecified whether a path object for that file is included.If the path is not a directory or otherwise inaccessible,
OSError
is raised.
- Path.glob(pattern, *, case_sensitive=None, recurse_symlinks=False)¶
現在のパスが表すディレクトリ内で相対 pattern に一致する (あらゆる種類の) すべてのファイルを yield します:
>>> 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')]
参考
Pattern language documentation.
デフォルトまたは case_sensitive キーワード専用引数に
None
を指定した場合、このメソッドはパスの一致判定にプラットフォームに依存した大文字小文字のルールを使用します。一般的にPOSIXは大文字と小文字を区別し、Windowsは区別しません。case_sensitive をTrue
またはFalse
に設定するとこの動作を上書きします。By default, or when the recurse_symlinks keyword-only argument is set to
False
, this method follows symlinks except when expanding "**
" wildcards. Set recurse_symlinks toTrue
to always follow symlinks.引数
self
,pattern
を指定して 監査イベントpathlib.Path.glob
を送出します。バージョン 3.12 で変更: case_sensitive 引数が追加されました。
バージョン 3.13 で変更: The recurse_symlinks parameter was added.
バージョン 3.13 で変更: The pattern parameter accepts a path-like object.
バージョン 3.13 で変更: Any
OSError
exceptions raised from scanning the filesystem are suppressed. In previous versions, such exceptions are suppressed in many cases, but not all.
- Path.rglob(pattern, *, case_sensitive=None, recurse_symlinks=False)¶
Glob the given relative pattern recursively. This is like calling
Path.glob()
with "**/
" added in front of the pattern.参考
Pattern language and
Path.glob()
documentation.引数
self
,pattern
を指定して 監査イベントpathlib.Path.rglob
を送出します。バージョン 3.12 で変更: case_sensitive 引数が追加されました。
バージョン 3.13 で変更: The recurse_symlinks parameter was added.
バージョン 3.13 で変更: The pattern parameter accepts a path-like object.
- Path.walk(top_down=True, on_error=None, follow_symlinks=False)¶
Generate the file names in a directory tree by walking the tree either top-down or bottom-up.
For each directory in the directory tree rooted at self (including self but excluding '.' and '..'), the method yields a 3-tuple of
(dirpath, dirnames, filenames)
.dirpath is a
Path
to the directory currently being walked, dirnames is a list of strings for the names of subdirectories in dirpath (excluding'.'
and'..'
), and filenames is a list of strings for the names of the non-directory files in dirpath. To get a full path (which begins with self) to a file or directory in dirpath, dodirpath / name
. Whether or not the lists are sorted is file system-dependent.If the optional argument top_down is true (which is the default), the triple for a directory is generated before the triples for any of its subdirectories (directories are walked top-down). If top_down is false, the triple for a directory is generated after the triples for all of its subdirectories (directories are walked bottom-up). No matter the value of top_down, the list of subdirectories is retrieved before the triples for the directory and its subdirectories are walked.
When top_down is true, the caller can modify the dirnames list in-place (for example, using
del
or slice assignment), andPath.walk()
will only recurse into the subdirectories whose names remain in dirnames. This can be used to prune the search, or to impose a specific order of visiting, or even to informPath.walk()
about directories the caller creates or renames before it resumesPath.walk()
again. Modifying dirnames when top_down is false has no effect on the behavior ofPath.walk()
since the directories in dirnames have already been generated by the time dirnames is yielded to the caller.By default, errors from
os.scandir()
are ignored. If the optional argument on_error is specified, it should be a callable; it will be called with one argument, anOSError
instance. The callable can handle the error to continue the walk or re-raise it to stop the walk. Note that the filename is available as thefilename
attribute of the exception object.By default,
Path.walk()
does not follow symbolic links, and instead adds them to the filenames list. Set follow_symlinks to true to resolve symlinks and place them in dirnames and filenames as appropriate for their targets, and consequently visit directories pointed to by symlinks (where supported).注釈
follow_symlinks に True を指定すると、シンボリックリンクが親ディレクトリを指していた場合に、無限ループになることに注意してください。
Path.walk()
はすでにたどったディレクトリを管理したりはしません。注釈
Path.walk()
assumes the directories it walks are not modified during execution. For example, if a directory from dirnames has been replaced with a symlink and follow_symlinks is false,Path.walk()
will still try to descend into it. To prevent such behavior, remove directories from dirnames as appropriate.注釈
Unlike
os.walk()
,Path.walk()
lists symlinks to directories in filenames if follow_symlinks is false.This example displays the number of bytes used by all files in each directory, while ignoring
__pycache__
directories:from pathlib import Path for root, dirs, files in Path("cpython/Lib/concurrent").walk(on_error=print): print( root, "consumes", sum((root / file).stat().st_size for file in files), "bytes in", len(files), "non-directory files" ) if '__pycache__' in dirs: dirs.remove('__pycache__')
This next example is a simple implementation of
shutil.rmtree()
. Walking the tree bottom-up is essential asrmdir()
doesn't allow deleting a directory before it is empty:# Delete everything reachable from the directory "top". # CAUTION: This is dangerous! For example, if top == Path('/'), # it could delete all of your files. for root, dirs, files in top.walk(top_down=False): for name in files: (root / name).unlink() for name in dirs: (root / name).rmdir()
Added in version 3.12.
Creating files and directories¶
- Path.touch(mode=0o666, exist_ok=True)¶
Create a file at this given path. If mode is given, it is combined with the process's
umask
value to determine the file mode and access flags. If the file already exists, the function succeeds when exist_ok is true (and its modification time is updated to the current time), otherwiseFileExistsError
is raised.参考
The
open()
,write_text()
andwrite_bytes()
methods are often used to create files.
- Path.mkdir(mode=0o777, parents=False, exist_ok=False)¶
Create a new directory at this given path. If mode is given, it is combined with the process's
umask
value to determine the file mode and access flags. If the path already exists,FileExistsError
is raised.parents の値が真の場合、このパスの親ディレクトリを必要に応じて作成します; それらのアクセス制限はデフォルト値が取られ、mode は使用されません (POSIX の
mkdir -p
コマンドを真似ています)。parents の値が偽の場合 (デフォルト)、親ディレクトリがないと
FileNotFoundError
を送出します。exist_ok の値が (デフォルトの) 偽の場合、対象のディレクトリがすでに存在すると
FileExistsError
を送出します。If exist_ok is true,
FileExistsError
will not be raised unless the given path already exists in the file system and is not a directory (same behavior as the POSIXmkdir -p
command).バージョン 3.5 で変更: exist_ok 引数が追加されました。
- Path.symlink_to(target, target_is_directory=False)¶
Make this path a symbolic link pointing to target.
On Windows, a symlink represents either a file or a directory, and does not morph to the target dynamically. If the target is present, the type of the symlink will be created to match. Otherwise, the symlink will be created as a directory if target_is_directory is true or a file symlink (the default) otherwise. On non-Windows platforms, target_is_directory is ignored.
>>> 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()
とは逆です。バージョン 3.13 で変更: Raises
UnsupportedOperation
ifos.symlink()
is not available. In previous versions,NotImplementedError
was raised.
- Path.hardlink_to(target)¶
このパスを target と同じファイルへのハードリンクにします。
注釈
引数の並び (link, target) は
os.link()
とは逆です。Added in version 3.10.
バージョン 3.13 で変更: Raises
UnsupportedOperation
ifos.link()
is not available. In previous versions,NotImplementedError
was raised.
Copying, renaming and deleting¶
- Path.copy(target, *, follow_symlinks=True)¶
Copy the contents of this file to the target file. If target specifies a file that already exists, it will be replaced.
If follow_symlinks is false, and this file is a symbolic link, target will be created as a symbolic link. If follow_symlinks is true and this file is a symbolic link, target will be a copy of the symlink target.
注釈
This method uses operating system functionality to copy file content efficiently. The OS might also copy some metadata, such as file permissions. After the copy is complete, users may wish to call
Path.chmod()
to set the permissions of the target file.警告
On old builds of Windows (before Windows 10 build 19041), this method raises
OSError
when a symlink to a directory is encountered and follow_symlinks is false.Added in version 3.14.
- Path.copytree(target, *, follow_symlinks=True, dirs_exist_ok=False, ignore=None, on_error=None)¶
Recursively copy this directory tree to the given destination.
If a symlink is encountered in the source tree, and follow_symlinks is true (the default), the symlink's target is copied. Otherwise, the symlink is recreated in the destination tree.
If the destination is an existing directory and dirs_exist_ok is false (the default), a
FileExistsError
is raised. Otherwise, the copying operation will continue if it encounters existing directories, and files within the destination tree will be overwritten by corresponding files from the source tree.If ignore is given, it should be a callable accepting one argument: a file or directory path within the source tree. The callable may return true to suppress copying of the path.
If on_error is given, it should be a callable accepting one argument: an instance of
OSError
. The callable may re-raise the exception or do nothing, in which case the copying operation continues. If on_error isn't given, exceptions are propagated to the caller.Added in version 3.14.
- 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'
The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the
Path
object.It is implemented in terms of
os.rename()
and gives the same guarantees.バージョン 3.8 で変更: Added return value, return the new
Path
instance.
- 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.The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the
Path
object.バージョン 3.8 で変更: Added return value, return the new
Path
instance.
- Path.unlink(missing_ok=False)¶
このファイルまたはシンボリックリンクを削除します。パスがディレクトリを指している場合は
Path.rmdir()
を使用してください。missing_ok の値が (デフォルトの) 偽の場合、対象のファイルが存在しないと
FileNotFoundError
を送出します。missing_ok の値が真の場合、
FileExistsError
例外を送出しません (POSIX のrm -f
コマンドの挙動と同じ)。バージョン 3.8 で変更: missing_ok 引数が追加されました。
- Path.rmdir()¶
現在のディレクトリを削除します。ディレクトリは空でなければなりません。
Permissions and ownership¶
- Path.owner(*, follow_symlinks=True)¶
Return the name of the user owning the file.
KeyError
is raised if the file's user identifier (UID) isn't found in the system database.This method normally follows symlinks; to get the owner of the symlink, add the argument
follow_symlinks=False
.バージョン 3.13 で変更: Raises
UnsupportedOperation
if thepwd
module is not available. In earlier versions,NotImplementedError
was raised.バージョン 3.13 で変更: follow_symlinks パラメータが追加されました。
- Path.group(*, follow_symlinks=True)¶
Return the name of the group owning the file.
KeyError
is raised if the file's group identifier (GID) isn't found in the system database.This method normally follows symlinks; to get the group of the symlink, add the argument
follow_symlinks=False
.バージョン 3.13 で変更: Raises
UnsupportedOperation
if thegrp
module is not available. In earlier versions,NotImplementedError
was raised.バージョン 3.13 で変更: follow_symlinks パラメータが追加されました。
- Path.chmod(mode, *, follow_symlinks=True)¶
os.chmod()
のようにファイルのモードとアクセス権限を変更します。このメソッドは通常シンボリックリンクをたどります。一部のUnixではシンボリックリンク自体のパーミッション変更をサポートしています。そのようなプラットフォームでは引数に``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.lchmod(mode)¶
Path.chmod()
のように振る舞いますが、パスがシンボリックリンクを指していた場合、リンク先ではなくシンボリックリンク自身のモードが変更されます。
その他のメソッド¶
- classmethod Path.cwd()¶
(
os.getcwd()
が返す) 現在のディレクトリを表す新しいパスオブジェクトを返します:>>> Path.cwd() PosixPath('/home/antoine/pathlib')
- classmethod Path.home()¶
ユーザーのホームディレクトリ (
os.path.expanduser()
での~
の返り値) を表す新しいパスオブジェクトを返します。ホームディレクトリが解決できない場合は、RuntimeError
を送出します。>>> Path.home() PosixPath('/home/antoine')
Added in version 3.5.
- Path.expanduser()¶
パス要素
~
および~user
をos.path.expanduser()
が返すように展開した新しいパスオブジェクトを返します。ホームディレクトリが解決できない場合は、RuntimeError
を送出します。>>> p = PosixPath('~/films/Monty Python') >>> p.expanduser() PosixPath('/home/eric/films/Monty Python')
Added in version 3.5.
- Path.readlink()¶
(
os.readlink()
が返す) シンボリックリンクが指すパスを返します:>>> p = Path('mylink') >>> p.symlink_to('setup.py') >>> p.readlink() PosixPath('setup.py')
Added in version 3.9.
バージョン 3.13 で変更: Raises
UnsupportedOperation
ifos.readlink()
is not available. In previous versions,NotImplementedError
was raised.
- Path.absolute()¶
正規化やシンボリックリンクの解決をせずに、パスを絶対パスにします。新しいパスオブジェクトを返します:
>>> 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')
If a path doesn't exist or a symlink loop is encountered, and strict is
True
,OSError
is raised. If strict isFalse
, the path is resolved as far as possible and any remainder is appended without checking whether it exists.バージョン 3.6 で変更: strict 引数を追加しました(3.6以前の挙動は strict です)。
バージョン 3.13 で変更: Symlink loops are treated like other errors:
OSError
is raised in strict mode, and no exception is raised in non-strict mode. In previous versions,RuntimeError
is raised no matter the value of strict.
Pattern language¶
The following wildcards are supported in patterns for
full_match()
, glob()
and rglob()
:
**
(entire segment)Matches any number of file or directory segments, including zero.
*
(entire segment)Matches one file or directory segment.
*
(part of a segment)Matches any number of non-separator characters, including zero.
?
Matches one non-separator character.
[seq]
Matches one character in seq.
[!seq]
Matches one character not in seq.
For a literal match, wrap the meta-characters in brackets.
For example, "[?]"
matches the character "?"
.
The "**
" wildcard enables recursive globbing. A few examples:
Pattern |
意味 |
---|---|
" |
Any path with at least one segment. |
" |
Any path with a final segment ending " |
" |
Any path starting with " |
" |
Any path starting with " |
注釈
Globbing with the "**
" wildcard visits every directory in the tree.
Large directory trees may take a long time to search.
バージョン 3.13 で変更: Globbing with a pattern that ends with "**
" returns both files and
directories. In previous versions, only directories were returned.
In Path.glob()
and rglob()
, a trailing slash may be added to
the pattern to match only directories.
Comparison to the glob
module¶
The patterns accepted and results generated by Path.glob()
and
Path.rglob()
differ slightly from those by the glob
module:
Files beginning with a dot are not special in pathlib. This is like passing
include_hidden=True
toglob.glob()
."
**
" pattern components are always recursive in pathlib. This is like passingrecursive=True
toglob.glob()
."
**
" pattern components do not follow symlinks by default in pathlib. This behaviour has no equivalent inglob.glob()
, but you can passrecurse_symlinks=True
toPath.glob()
for compatible behaviour.Like all
PurePath
andPath
objects, the values returned fromPath.glob()
andPath.rglob()
don't include trailing slashes.The values returned from pathlib's
path.glob()
andpath.rglob()
include the path as a prefix, unlike the results ofglob.glob(root_dir=path)
.The values returned from pathlib's
path.glob()
andpath.rglob()
may include path itself, for example when globbing "**
", whereas the results ofglob.glob(root_dir=path)
never include an empty string that would correspond to path.
Comparison to the os
and os.path
modules¶
pathlib implements path operations using PurePath
and Path
objects, and so it's said to be object-oriented. On the other hand, the
os
and os.path
modules supply functions that work with low-level
str
and bytes
objects, which is a more procedural approach. Some
users consider the object-oriented style to be more readable.
Many functions in os
and os.path
support bytes
paths and
paths relative to directory descriptors. These features aren't
available in pathlib.
Python's str
and bytes
types, and portions of the os
and
os.path
modules, are written in C and are very speedy. pathlib is
written in pure Python and is often slower, but rarely slow enough to matter.
pathlib's path normalization is slightly more opinionated and consistent than
os.path
. For example, whereas os.path.abspath()
eliminates
"..
" segments from a path, which may change its meaning if symlinks are
involved, Path.absolute()
preserves these segments for greater safety.
pathlib's path normalization may render it unsuitable for some applications:
pathlib normalizes
Path("my_folder/")
toPath("my_folder")
, which changes a path's meaning when supplied to various operating system APIs and command-line utilities. Specifically, the absence of a trailing separator may allow the path to be resolved as either a file or directory, rather than a directory only.pathlib normalizes
Path("./my_program")
toPath("my_program")
, which changes a path's meaning when used as an executable search path, such as in a shell or when spawning a child process. Specifically, the absence of a separator in the path may force it to be looked up inPATH
rather than the current directory.
As a consequence of these differences, pathlib is not a drop-in replacement
for os.path
.
Corresponding tools¶
下にあるのは、様々な os
関数とそれに相当する PurePath
あるいは Path
の同等のものとの対応表です。