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

バージョン 3.4 で追加.

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

======================================================================

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

[画像]

あなたが今までこのモジュールを使用したことがない場合や、タスクに適して
いるのがどのクラスかわからない場合は、 "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')

   *pathsegments* の各要素は、部分パスの文字列表現か、文字列を返す
   "os.PathLike" インターフェイスを実装しているオブジェクトか、その他
   の path オブジェクトです。

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

   *pathsegments* が空のとき、現在のディレクトリとみなされます:

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

   If a segment is an absolute path, all previous segments are ignored
   (like "os.path.join()"):

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

   On Windows, the drive is not reset when a rooted relative path
   segment (e.g., "r'\foo'") is encountered:

      >>> 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" と同じです。

これらクラスはあらゆるシステムコールを行わないため、起動しているシステ
ムにかかわらずインスタンスを作成できます。


全般的な性質
------------

Paths are immutable and *hashable*.  Paths of a same flavour are
comparable and orderable.  These properties respect the flavour's
case-folding semantics:

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


演算子
------

The slash operator helps create child paths, like "os.path.join()". If
the argument is an absolute path, the previous path is ignored. On
Windows, the drive is not reset when the argument is a rooted relative
path (e.g., "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" でパスの先頭が３つ以上の連続したスラッシュである場
   合、 余分なスラッシュは除去されます:

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

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

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

   バージョン 3.9 で追加.

PurePath.is_reserved()

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

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

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

PurePath.joinpath(*other)

   このメソッドの呼び出しは引数 *other* を順々に繋げることと等価になり
   ます:

      >>> PurePosixPath('/etc').joinpath('passwd')
      PurePosixPath('/etc/passwd')
      >>> PurePosixPath('/etc').joinpath(PurePosixPath('passwd'))
      PurePosixPath('/etc/passwd')
      >>> PurePosixPath('/etc').joinpath('init.d', 'apache2')
      PurePosixPath('/etc/init.d/apache2')
      >>> PureWindowsPath('c:').joinpath('/Program Files')
      PureWindowsPath('c:/Program Files')

PurePath.match(pattern)

   現在のパスが 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)

   *other* で表されたパスから現在のパスへの相対パスを返します。それが
   不可能だった場合は ValueError が送出されます:

      >>> p = PurePosixPath('/etc/passwd')
      >>> p.relative_to('/')
      PurePosixPath('etc/passwd')
      >>> p.relative_to('/etc')
      PurePosixPath('passwd')
      >>> p.relative_to('/usr')
      Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
        File "pathlib.py", line 694, in relative_to
          .format(str(self), str(formatted)))
      ValueError: '/etc/passwd' is not in the subpath of '/usr' OR one path is relative and the other absolute.

   注記: この関数は "PurePath" の一部分であり、文字列で処理を行います
   。 根底のファイル構造をチェックしたりアクセスしたりはしません。

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" のサブクラスであり、システムのパスフレーバーの具象パスを
   表します (このインスタンスの作成で "PosixPath" か "WindowsPath" の
   どちらかが作成されます):

      >>> 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()" のようにファイルのモードとアクセス権限を変更します。

   This method normally follows symlinks. Some Unix flavours support
   changing permissions on the symlink itself; on these platforms you
   may add the argument "follow_symlinks=False", or use "lchmod()".

      >>> p = Path('setup.py')
      >>> p.stat().st_mode
      33277
      >>> p.chmod(0o444)
      >>> p.stat().st_mode
      33060

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

Path.exists()

   パスが既存のファイルかディレクトリを指しているかどうかを返します:

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

   注釈:

     パスがシンボリックリンクを指している場合、"exists()" はシンボリッ
     クリンクが既存のファイルかディレクトリを指しているかどうかを返し
     ます。

Path.expanduser()

   パス要素 "~" および "~user" を "os.path.expanduser()" が返すように
   展開した新しいパスオブジェクトを返します。ホームディレクトリが解決
   できない場合は、 "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')]

   Patterns are the same as for "fnmatch", with the addition of ""**""
   which means "this directory and all subdirectories, recursively".
   In other words, it enables recursive globbing:

      >>> 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"
   を送出します。

Path.group()

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

Path.is_dir()

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

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

Path.is_file()

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

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

Path.is_mount()

   パス名 *path* がマウントポイント *mount point* (ファイルシステムの
   中で異なるファイルシステムがマウントされているところ) なら "True"
   を返します。 POSIX では、この関数は *path* の親ディレクトリである
   "path/.." が *path* と異なるデバイス上にあるか、あるいは "path/.."
   と *path* が同じデバイス上の同じ i-node を指しているかをチェックし
   ます --- これによってすべての Unix と POSIX 系システムでマウントポ
   イントが検出できます。 この関数は Windows では実装されていません。

   バージョン 3.7 で追加.

Path.is_symlink()

   パスがシンボリックリンクを指していた場合 "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')

   The children are yielded in arbitrary order, and the special
   entries "'.'" and "'..'" are not included.  If a file is removed
   from or added to the directory after creating the iterator, whether
   a path object for that file be included is unspecified.

Path.lchmod(mode)

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

Path.lstat()

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

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

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

   *parents* の値が真の場合、このパスの親ディレクトリを必要に応じて作
   成します; それらのアクセス制限はデフォルト値が取られ、*mode* は使用
   されません (POSIX の "mkdir -p" コマンドを真似ています)。

   *parents* の値が偽の場合 (デフォルト)、親ディレクトリがないと
   "FileNotFoundError" を送出します。

   *exist_ok* の値が (デフォルトの) 偽の場合、対象のディレクトリがすで
   に存在すると "FileExistsError" を送出します。

   *exist_ok* の値が真の場合、パス要素の末尾がすでに存在するがディレク
   トリではないときは "FileExistsError" 例外を送出しますが、ディレクト
   リであれば送出しません (POSIX の "mkdir -p" コマンドの挙動と同じ)。

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

Path.readlink()

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

   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)

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

   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.resolve(strict=False)

   パスを絶対パスにし、あらゆるシンボリックリンクを解決します。新しい
   パスオブジェクトが返されます:

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

   "".."" 要素は除去されます (このような挙動を示すのはこのメソッドだけ
   です):

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

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

   バージョン 3.6 で追加: *strict* 引数 (3.6以前の挙動は strict です。
   )

Path.rglob(pattern)

   これは "Path.glob()" を *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"
   を送出します。

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

Path.symlink_to(target, target_is_directory=False)

   現在のパスに *target* へのシンボリックリンクを作成します。Windows
   では、リンク対象がディレクトリの場合 *target_is_directory* が真でな
   ければなりません (デフォルトは "False")。POSIX では、
   *target_is_directory* の値は無視されます。

      >>> p = Path('mylink')
      >>> p.symlink_to('setup.py')
      >>> p.resolve()
      PosixPath('/home/antoine/pathlib/setup.py')
      >>> p.stat().st_size
      956
      >>> p.lstat().st_size
      8

   注釈:

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

Path.hardlink_to(target)

   Make this path a hard link to the same file as *target*.

   注釈:

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

   バージョン 3.10 で追加.

Path.link_to(target)

   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.unlink(missing_ok=False)

   このファイルまたはシンボリックリンクを削除します。パスがディレクト
   リを指している場合は "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'

   An existing file of the same name is overwritten. The optional
   parameters have the same meaning as in "open()".

   バージョン 3.5 で追加.

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


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

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

注釈:

  Not all pairs of functions/methods below are equivalent. Some of
  them, despite having some overlapping use-cases, have different
  semantics. They include "os.path.abspath()" and "Path.resolve()",
  "os.path.relpath()" and "PurePath.relative_to()".

+--------------------------------------+-----------------------------------+
| "os" と "os.path"                    | "pathlib"                         |
|======================================|===================================|
| "os.path.abspath()"                  | "Path.resolve()" [1]              |
+--------------------------------------+-----------------------------------+
| "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" and               |
|                                      | "PurePath.suffix"                 |
+--------------------------------------+-----------------------------------+

-[ 脚注 ]-

[1] "os.path.abspath()" does not resolve symbolic links while
    "Path.resolve()" does.

[2] "PurePath.relative_to()" requires "self" to be the subpath of the
    argument, but "os.path.relpath()" does not.
