pathlib --- オブジェクト指向のファイルシステムパス

バージョン 3.4 で追加.

ソースコード: Lib/pathlib.py


このモジュールはファイルシステムのパスを表すクラスを提供していて、様々なオペレーティングシステムについての適切な意味論をそれらのクラスに持たせています。 Path クラスは 純粋パス具象パス からなります。 純粋パスは I/O を伴わない純粋な計算操作を提供します。 具象パスは純粋パスを継承していますが、 I/O 操作も提供しています。

../_images/pathlib-inheritance.png

あなたが今までこのモジュールを使用したことがない場合や、タスクに適しているのがどのクラスかわからない場合は、 Path はきっとあなたに必要なものでしょう。 Path はコードが実行されているプラットフォーム用の 具象パス のインスタンスを作成します。

純粋パスは、以下のようないくつかの特殊なケースで有用です:

  1. Unix マシン上で Windows のパスを扱いたいとき (またはその逆)。Unix 上で実行しているときに WindowsPath のインスタンスを作成することはできませんが、PureWindowsPath なら可能になります。

  2. 実際に 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'

純粋パス

純粋パスオブジェクトは実際にファイルシステムにアクセスしないパス操作処理を提供します。これらのクラスにアクセスするには 3 つの方法があり、それらを フレーバー と呼んでいます:

class pathlib.PurePath(*pathsegments)

システムのパスのフレーバーを表すジェネリッククラスです (インスタンスを作成することで PurePosixPath または PureWindowsPath のどちらかが作成されます):

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

Each element of pathsegments can be either a string representing a path segment, an object implementing the os.PathLike interface which returns a string, or another path object:

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

末尾の要素に拡張子があればそれになります:

>>> 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 URI で表したパスを返します。絶対パスではない場合に 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_relative_to(*other)

このパスが other パスに対して相対なのかそうでないのかの結果を返します。

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

If multiple arguments are supplied, they are joined together.

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

バージョン 3.9 で追加.

PurePath.is_reserved()

PureWindowsPath の場合はパスが Windows 上で予約されていれば True を返し、そうでなければ False を返します。PurePosixPath の場合は常に False を返します。

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

ファイルシステムで予約されたパスを呼び出すと、原因不明で失敗したり、予期せぬ結果になります。

PurePath.joinpath(*other)

Calling this method is equivalent to combining the path with each of the other arguments in turn:

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

現在のパスが glob 形式で与えられたパターンと一致したら 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

他のメソッドと同様に、大文字小文字の区別はプラットフォームの設定に従います:

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

Compute a version of this path relative to the path represented by other. If it's impossible, ValueError is raised:

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

If multiple arguments are supplied, they are joined together.

NOTE: This function is part of PurePath and works with strings. It does not check or access the underlying file structure.

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

バージョン 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 つの方法があります:

class pathlib.Path(*pathsegments)

PurePath のサブクラスであり、システムのパスフレーバーの具象パスを表します (このインスタンスの作成で PosixPathWindowsPath のどちらかが作成されます):

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

pathsegments の指定は PurePath と同じです。

class pathlib.PosixPath(*pathsegments)

Path および PurePosixPath のサブクラスで、非 Windows ファイルシステムの具象パスを表します:

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

pathsegments の指定は PurePath と同じです。

class pathlib.WindowsPath(*pathsegments)

Path および PureWindowsPath のサブクラスで、Windows ファイルシステムの具象パスを表します:

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

pathsegments の指定は PurePath と同じです。

インスタンスを作成できるのはシステムと一致するフレーバーのみです (互換性のないパスフレーバーでのシステムコールの許可はバグやアプリケーションの異常終了の原因になります):

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

メソッド

具象パスは純粋パスに加え、以下のメソッドを提供します。これらメソッドの多くはシステムコールが失敗すると OSError を送出します。(例えばパスが存在しない場合)

バージョン 3.8 で変更: exists(), is_dir(), is_file(), is_mount(), is_symlink(), is_block_device(), is_char_device(), is_fifo(), is_socket() は、OSレベルで表現不能な文字を含むパスに対して、例外を送出する代わりに False を返すようになりました。

classmethod Path.cwd()

(os.getcwd() が返す) 現在のディレクトリを表す新しいパスオブジェクトを返します:

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

ユーザーのホームディレクトリ (os.path.expanduser() での ~ の返り値) を表す新しいパスオブジェクトを返します。ホームディレクトリが解決できない場合は、 RuntimeError を送出します。

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

バージョン 3.5 で追加.

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

Whether the path points to an existing file or directory:

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

注釈

If the path points to a symlink, exists() returns whether the symlink points to an existing file or directory.

Path.expanduser()

パス要素 ~ および ~useros.path.expanduser() が返すように展開した新しいパスオブジェクトを返します。ホームディレクトリが解決できない場合は、 RuntimeError を送出します。

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

バージョン 3.5 で追加.

Path.glob(pattern)

現在のパスが表すディレクトリ内で相対 pattern に一致する (あらゆる種類の) すべてのファイルを yield します:

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

パターンは fnmatch と同じで、追加の ** は "このディレクトリおよびすべてのサブディレクトリを再帰的に走査" を意味します。言い換えれば、再帰的な Glob 走査が可能という意味です:

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

注釈

パターン "**" を大きなディレクトリツリーで使用するととてつもなく時間がかかるかもしれません。

引数 self, pattern を指定して 監査イベント pathlib.Path.glob を送出します。

バージョン 3.11 で変更: pattern がパスを分割する文字(sep または altsep)で終わる場合はディレクトリのみを返します。

Path.group()

ファイルを所有するグループ名を返します。ファイルの GID がシステムのデータベースに見つからなかった場合は KeyError が送出されます。

Path.is_dir()

パスがディレクトリ (またはディレクトリへのシンボリックリンク) を指していた場合 True を返し、その他の種類のファイルだった場合 False を返します。

パスが存在しないか壊れたシンボリックリンクだった場合にも False が返されます; (パーミッションエラーのような) その他のエラーは伝搬されます。

Path.is_file()

パスが一般ファイル (または一般ファイルへのシンボリックリンク) を指していた場合 True を返します。その他の種類のファイルを指していた場合 False を返します。

パスが存在しないか壊れたシンボリックリンクだった場合にも False が返されます; (パーミッションエラーのような) その他のエラーは伝搬されます。

Path.is_mount()

Return True if the path is a mount point: a point in a file system where a different file system has been mounted. On POSIX, the function checks whether path's parent, path/.., is on a different device than path, or whether path/.. and path point to the same i-node on the same device --- this should detect mount points for all Unix and POSIX variants. Not implemented on Windows.

バージョン 3.7 で追加.

パスがシンボリックリンクを指していた場合 True を返し、その他の場合は False を返します。

パスが存在しない場合も False を返します; (パーミッションエラーのような) その他のエラーは伝搬されます。

Path.is_socket()

パスが Unix ソケット (または Unix ソケットへのシンボリックリンク) を指していた場合 True を返します。その他の種類のファイルの場合 False を返します。

パスが存在しないか壊れたシンボリックリンクだった場合にも False が返されます; (パーミッションエラーのような) その他のエラーは伝搬されます。

Path.is_fifo()

パスが FIFO (または FIFO へのシンボリックリンク) を指していた場合 True を返します。その他の種類のファイルの場合は False を返します。

パスが存在しないか壊れたシンボリックリンクだった場合にも False が返されます; (パーミッションエラーのような) その他のエラーは伝搬されます。

Path.is_block_device()

パスがブロックデバイス (またはブロックデバイスへのシンボリックリンク) を指していた場合 True を返します。その他の種類のファイルの場合は False を返します。

パスが存在しないか壊れたシンボリックリンクだった場合にも False が返されます; (パーミッションエラーのような) その他のエラーは伝搬されます。

Path.is_char_device()

パスがキャラクターデバイス (またはキャラクターデバイスへのシンボリックリンク) を指していた場合、True を返します。その他の種類のファイルの場合 False を返します。

パスが存在しないか壊れたシンボリックリンクだった場合にも False が返されます; (パーミッションエラーのような) その他のエラーは伝搬されます。

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

子の要素は任意の順番で yield されます。特殊なパスの '.''..' は含まれません。イテレーターを生成したあとにディレクトリにファイルを削除または追加した場合に、そのファイルのパスオブジェクトが含まれるかは定義されていません。

Path.lchmod(mode)

Path.chmod() のように振る舞いますが、パスがシンボリックリンクを指していた場合、リンク先ではなくシンボリックリンク自身のモードが変更されます。

Path.lstat()

Path.stat() のように振る舞いますが、パスがシンボリックリンクを指していた場合、リンク先ではなくシンボリックリンク自身の情報を返します。

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

与えられたパスに新しくディレクトリを作成します。mode が与えられていた場合、プロセスの umask 値と組み合わせてファイルのモードとアクセスフラグを決定します。パスがすでに存在していた場合 FileExistsError が送出されます。

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 POSIX mkdir -p command).

バージョン 3.5 で変更: exist_ok 引数が追加されました。

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

ファイルの所有者のユーザー名を返します。ファイルの UID がシステムのデータベースに見つからない場合 KeyError が送出されます。

Path.read_bytes()

指定されたファイルの内容をバイナリオブジェクトで返します:

>>> 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 で追加.

( os.readlink() が返す) シンボリックリンクが指すパスを返します:

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

バージョン 3.9 で追加.

Path.rename(target)

このファイルかディレクトリを与えられた target にリネームし、 target を指すパスのインスタンスを返します。 Unix では target が存在するファイルの場合、ユーザにパーミッションがあれば静かに置換されます。 Windows では target が存在する場合、FileExistsError が送出されます。 target は文字列か別のパスオブジェクトです:

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

targetパスは絶対または相対で指定できます。相対パスは現在の作業ディレクトリからの相対パスとして解釈し、Pathオブジェクトのディレクトリ ではありません

It is implemented in terms of os.rename() and gives the same guarantees.

バージョン 3.8 で変更: 戻り値を追加し、新しい Path インスタンスを返します。

Path.replace(target)

現在のファイルまたはディレクトリの名前を target に変更し、 target を指すパスのインスタンスを返します。target が既存のファイルか空のディレクトリを指していた場合、無条件に置き換えられます。

targetパスは絶対または相対で指定できます。相対パスは現在の作業ディレクトリからの相対パスとして解釈し、Pathオブジェクトのディレクトリ ではありません

バージョン 3.8 で変更: 戻り値を追加し、新しい Path インスタンスを返します。

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

パスが存在せず strictTrue の場合、 FileNotFoundError が送出されます。 strictFalse の場合は、パスは可能な限り解決され、残りの部分は存在するかのチェックをせずに追加されます。 もしパスの解決にあたって無限ループする場合は、RuntimeError が送出されます。

バージョン 3.6 で追加: The strict argument (pre-3.6 behavior is strict).

Path.rglob(pattern)

This is like calling Path.glob() with "**/" added in front of the given relative pattern:

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

引数 self, pattern を指定して 監査イベント pathlib.Path.rglob を送出します。

バージョン 3.11 で変更: pattern がパスを分割する文字(sep または altsep)で終わる場合はディレクトリのみを返します。

Path.rmdir()

現在のディレクトリを削除します。ディレクトリは空でなければなりません。

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

バージョン 3.5 で追加.

Make this path a symbolic link pointing to target.

Windows では、シンボリックリンクはファイルかディレクトリのどちらかを表しますが、ターゲットに合わせて動的に変化することはありません。ターゲットが存在する場合、シンボリックリンクの種類は対象に合わせて作成されます。ターゲットが存在せず target_is_directoryTrue が設定された場合、シンボリックリンクはディレクトリのリンクとして作成され、False に設定された場合 (デフォルト) はファイルのリンクになります。Windows 以外のプラットフォームでは 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() とは逆です。

このパスを target と同じファイルへのハードリンクにします。

注釈

引数の並び (link, target) は os.link() とは逆です。

バージョン 3.10 で追加.

Make target a hard link to this path.

警告

This function does not make this path a hard link to target, despite the implication of the function and argument names. The argument order (target, link) is the reverse of Path.symlink_to() and Path.hardlink_to(), but matches that of os.link().

バージョン 3.8 で追加.

バージョン 3.10 で非推奨: This method is deprecated in favor of Path.hardlink_to(), as the argument order of Path.link_to() does not match that of Path.symlink_to().

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

与えられたパスにファイルを作成します。mode が与えられた場合、プロセスの umask 値と組み合わせてファイルのモードとアクセスフラグが決定されます。ファイルがすでに存在した場合、exist_ok が真ならばこの関数は正常に終了します (そしてファイルの更新日付が現在の日時に変更されます)。その他の場合は FileExistsError が送出されます。

このファイルまたはシンボリックリンクを削除します。パスがディレクトリを指している場合は Path.rmdir() を使用してください。

missing_ok の値が (デフォルトの) 偽の場合、対象のファイルが存在しないと FileNotFoundError を送出します。

missing_ok の値が真の場合、 FileExistsError 例外を送出しません (POSIX の rm -f コマンドの挙動と同じ)。

バージョン 3.8 で変更: missing_ok 引数が追加されました。

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'

同じ名前のファイルがすでにあれば上書きされます。

バージョン 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() と同じです。

バージョン 3.5 で追加.

バージョン 3.10 で変更: newline パラメータが追加されました。

os モジュールにあるツールとの対応付け

下にあるのは、様々な os 関数とそれに相当する PurePath あるいは Path の同等のものとの対応表です。

注釈

以下の関数とメソッドのペアは、全てが等価ではありません。いくつかのユースケースが共通しているが、異なる意味を持つものもあります。os.path.abspath()Path.absolute()os.path.relpath()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()

PurePath.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.stem および PurePath.suffix

脚注