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

バージョン 3.4 で追加.

Source code: Lib/pathlib/


このモジュールはファイルシステムのパスを表すクラスを提供していて、様々なオペレーティングシステムについての適切な意味論をそれらのクラスに持たせています。 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'

Exceptions

exception pathlib.UnsupportedOperation

An exception inheriting NotImplementedError that is raised when an unsupported operation is called on a path object.

バージョン 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: either posixpath or ntpath.

バージョン 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 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

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.

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

バージョン 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 or False to override this behaviour.

バージョン 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.

walk_up がFalseの場合(デフォルト)、パスは other から始まる必要があります。引数に True を指定すると .. を追加して相対パスを作成する場合があります。異なるドライブを参照するなど、それ以外のケースでは ValueError が送出されます。:

>>> 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; call resolve() 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

バージョン 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')
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 and relative_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

バージョン 3.12 で追加.

具象パス

具象パスは純粋パスクラスのサブクラスです。純粋パスが提供する操作に加え、パスオブジェクト上でシステムコールを呼ぶメソッドも提供しています。具象パスのインスタンスを作成するには 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 と同じです。

バージョン 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

File 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 with file:, or the parsed path isn't absolute.

バージョン 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 of os.fsencode() makes it strictly impure.

メソッド

具象パスは純粋パスに加え、以下のメソッドを提供します。これらメソッドの多くはシステムコールが失敗すると 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(*, follow_symlinks=True)

パスが存在するファイルかディレクトリを指している場合は True を返します。

このメソッドは通常はシンボリックリンクをたどります。シンボリックリンクが存在するかを確認したい場合は follow_symlinks=False 引数を追加してください。

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

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

Path.expanduser()

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

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

バージョン 3.5 で追加.

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_sensitiveTrue または 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 to True 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.group(*, follow_symlinks=True)

Return the name of the group owning the file. KeyError is raised if the file's 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 the grp module is not available. In previous versions, NotImplementedError was raised.

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

Path.is_dir(*, follow_symlinks=True)

Return True if the path points to a directory, False if it points to another kind of file.

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

This method normally follows symlinks; to exclude symlinks to directories, add the argument follow_symlinks=False.

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

Path.is_file(*, follow_symlinks=True)

Return True if the path points to a regular file, False if it points to another kind of file.

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

This method normally follows symlinks; to exclude symlinks, add the argument follow_symlinks=False.

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

Path.is_junction()

パスがジャンクションを指している場合は True を返し、それ以外の場合は False を返します。現在はWindowsのみジャンクションをサポートしています。

バージョン 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)またはマウントされたファイルシステムのディレクトリです。

バージョン 3.7 で追加.

バージョン 3.12 で変更: Windows のサポートが追加されました。

パスがシンボリックリンクを指していた場合 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.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, do dirpath / 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), and Path.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 inform Path.walk() about directories the caller creates or renames before it resumes Path.walk() again. Modifying dirnames when top_down is false has no effect on the behavior of Path.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, an OSError 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 the filename 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 as rmdir() 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()

バージョン 3.12 で追加.

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(*, follow_symlinks=True)

Return the name of the user owning the file. KeyError is raised if the file's 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 the pwd module is not available. In previous versions, NotImplementedError was raised.

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

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, newline=None)

指定されたファイルの内容を文字列としてデコードして返します:

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

ファイルを開いた後に閉じます。 オプションのパラメーターの意味は open() と同じです。

バージョン 3.5 で追加.

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

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

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

バージョン 3.9 で追加.

バージョン 3.13 で変更: Raises UnsupportedOperation if os.readlink() is not available. In previous versions, NotImplementedError was raised.

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

If a path doesn't exist or a symlink loop is encountered, and strict is True, OSError is raised. If strict is False, 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.

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() とは逆です。

バージョン 3.13 で変更: Raises UnsupportedOperation if os.symlink() is not available. In previous versions, NotImplementedError was raised.

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

注釈

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

バージョン 3.10 で追加.

バージョン 3.13 で変更: Raises UnsupportedOperation if os.link() is not available. In previous versions, NotImplementedError was raised.

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 パラメータが追加されました。

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

Meaning

"**/*"

Any path with at least one segment.

"**/*.py"

Any path with a final segment ending ".py".

"assets/**"

Any path starting with "assets/".

"assets/**/*"

Any path starting with "assets/", excluding "assets/" itself.

注釈

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.

バージョン 3.11 で変更: Globbing with a pattern that ends with a pathname components separator (sep or altsep) returns 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:

  1. Files beginning with a dot are not special in pathlib. This is like passing include_hidden=True to glob.glob().

  2. "**" pattern components are always recursive in pathlib. This is like passing recursive=True to glob.glob().

  3. "**" pattern components do not follow symlinks by default in pathlib. This behaviour has no equivalent in glob.glob(), but you can pass recurse_symlinks=True to Path.glob() for compatible behaviour.

  4. Like all PurePath and Path objects, the values returned from Path.glob() and Path.rglob() don't include trailing slashes.

  5. The values returned from pathlib's path.glob() and path.rglob() include the path as a prefix, unlike the results of glob.glob(root_dir=path).

  6. The values returned from pathlib's path.glob() and path.rglob() may include path itself, for example when globbing "**", whereas the results of glob.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:

  1. pathlib normalizes Path("my_folder/") to Path("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.

  2. pathlib normalizes Path("./my_program") to Path("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 in PATH 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 の同等のものとの対応表です。

osos.path

pathlib

os.path.abspath()

Path.absolute()

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

Path.walk()

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

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