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

Added in version 3.4.

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

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

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

[画像: Inheritance diagram showing the classes available in pathlib.
The most basic class is PurePath, which has three direct subclasses:
PurePosixPath, PureWindowsPath, and Path. Further to these four
classes, there are two classes that use multiple inheritance:
PosixPath subclasses PurePosixPath and Path, and WindowsPath
subclasses PureWindowsPath and Path.][画像]

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


例外
====

exception pathlib.UnsupportedOperation

   "NotImplementedError" を継承した例外です。パスオブジェクトがサポー
   トしていない操作を行おうとした時に送出されます。

   Added in version 3.13.


純粋パス
========

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

class pathlib.PurePath(*pathsegments)

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

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

   *pathsegments* の各要素は、パスの構成要素を表す文字列か、パスオブジ
   ェクトなどの、 "os.PathLike" インターフェースを実装するオブジェクト
   である必要があります。 "os.PathLike" インターフェースでは、
   "__fspath__()" メソッドが文字列を返します:

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

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

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

   あるパス構成要素が絶対パスである場合、それより前の要素はすべて無視
   されます ("os.path.join()" と同様):

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

   Windowsの場合、ルート相対パス (例えば "r'\foo'") があってもドライブ
   名はそのまま変わりません:

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

   単一スラッシュと等価な複数スラッシュやシングルドットは簡略化されま
   すが、ダブルドット ("'..'") や先頭に位置するダブルスラッシュ
   ("'//'") は簡略化されません。 これは、様々な理由でパスの意味が簡略
   化した場合と異なってしまうからです (例: シンボリックリンク、UNCパス
   ):

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

   (通常 "PurePosixPath('foo/../bar')" は "PurePosixPath('bar')" と等
   価になりますが、"foo" が他のディレクトリへのシンボリックリンクの場
   合は等価になりません)

   純粋パスオブジェクトは "os.PathLike" インターフェースを実装しており
   、そのインターフェースを受理する箇所ならどこでも使用することができ
   ます。

   バージョン 3.6 で変更: "os.PathLike" インターフェースがサポートされ
   ました。

class pathlib.PurePosixPath(*pathsegments)

   "PurePath" のサブクラスです。このパスフレーバーは非 Windows パスを
   表します:

      >>> PurePosixPath('/etc/hosts')
      PurePosixPath('/etc/hosts')

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

class pathlib.PureWindowsPath(*pathsegments)

   "PurePath" のサブクラスです。このパスフレーバー UNC paths を含む
   Windows ファイルシステムパスを表します:

      >>> PureWindowsPath('c:/', 'Users', 'Ximénez')
      PureWindowsPath('c:/Users/Ximénez')
      >>> PureWindowsPath('//server/share/file')
      PureWindowsPath('//server/share/file')

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

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


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

パスオブジェクトはイミュータブルで *ハッシュ可能* です。同じフレーバー
のパスオブジェクトは比較ならびに順序付け可能です。これらのプロパティは
、フレーバーのケースフォールディング (訳注: 比較のために正規化すること
、例えば全て大文字にする) のセマンティクスに従います。

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

   低レベルのパスのパースと結合に使用される "os.path" モジュールの実装
   。"posixpath" または "ntpath"。

   Added in version 3.13.

PurePath.drive

   ドライブ文字または名前を表す文字列があればそれになります:

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

   UNC 共有名もドライブとみなされます:

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

PurePath.root

   ローカルまたはグローバルルートを表す文字列があればそれになります:

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

   UNC 共有名は常にルートを持ちます:

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

   "PurePosixPath" でパスの先頭が３つ以上の連続したスラッシュである場
   合、 余分なスラッシュは除去されます:

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

   一般的にはファイル拡張子と呼ばれています。

   バージョン 3.14 で変更: A single dot (""."") is considered a valid
   suffix.

PurePath.suffixes

   パスのサフィックス(ファイル拡張子)のリストです:

      >>> PurePosixPath('my/library.tar.gar').suffixes
      ['.tar', '.gar']
      >>> PurePosixPath('my/library.tar.gz').suffixes
      ['.tar', '.gz']
      >>> PurePosixPath('my/library').suffixes
      []

   バージョン 3.14 で変更: A single dot (""."") is considered a valid
   suffix.

PurePath.stem

   パス要素の末尾から拡張子を除いたものになります:

      >>> PurePosixPath('my/library.tar.gz').stem
      'library.tar'
      >>> PurePosixPath('my/library.tar').stem
      'library'
      >>> PurePosixPath('my/library').stem
      'library'

PurePath.as_posix()

   フォワードスラッシュ ("/") を使用したパスを表す文字列を返します:

      >>> p = PureWindowsPath('c:\\windows')
      >>> str(p)
      'c:\\windows'
      >>> p.as_posix()
      'c:/windows'

PurePath.is_absolute()

   パスが絶対パスかどうかを返します。パスが絶対パスとみなされるのは、
   ルートと (フレーバーが許す場合) ドライブとの両方が含まれる場合です:

      >>> PurePosixPath('/a/b').is_absolute()
      True
      >>> PurePosixPath('a/b').is_absolute()
      False

      >>> PureWindowsPath('c:/a/b').is_absolute()
      True
      >>> PureWindowsPath('/a/b').is_absolute()
      False
      >>> PureWindowsPath('c:').is_absolute()
      False
      >>> PureWindowsPath('//some/share').is_absolute()
      True

PurePath.is_relative_to(other)

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

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

   This method is string-based; it neither accesses the filesystem nor
   treats "".."" segments specially. The following code is equivalent:

   >>> u = PurePath('/usr')
   >>> u == p or u in p.parents
   False

   Added in version 3.9.

   Deprecated since version 3.12, removed in version 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.

   Deprecated since version 3.13, will be removed in version 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)

   現在のパスが glob 形式で与えられたパターンと一致したら "True" を、
   一致しなければ "False" を返します。例:

      >>> 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 ドキュメント。

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

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

   Added in version 3.13.

PurePath.match(pattern, *, case_sensitive=None)

   現在のパスが非再帰の glob 形式で与えられたパターンと一致したら
   "True" を、一致しなければ "False" を返します。

   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 で変更: *pattern* パラメタが *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" を指定すると以前の動作と同じになります）。

   Deprecated since version 3.12, removed in version 3.14: 追加の位置
   引数の指定は非推奨となりました。指定された場合は *other* と連結され
   ます。

PurePath.with_name(name)

   現在のパスの "name" 部分を変更したパスを返します。オリジナルパスに
   "name" 部分がない場合は ValueError が送出されます:

      >>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
      >>> p.with_name('setup.py')
      PureWindowsPath('c:/Downloads/setup.py')
      >>> p = PureWindowsPath('c:/')
      >>> p.with_name('setup.py')
      Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
        File "/home/antoine/cpython/default/Lib/pathlib.py", line 751, in with_name
          raise ValueError("%r has an empty name" % (self,))
      ValueError: PureWindowsPath('c:/') has an empty name

PurePath.with_stem(stem)

   現在のパスの "stem" 部分を変更したパスを返します。オリジナルパスに
   "stem" 部分がない場合は ValueError が送出されます:

      >>> p = PureWindowsPath('c:/Downloads/draft.txt')
      >>> p.with_stem('final')
      PureWindowsPath('c:/Downloads/final.txt')
      >>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
      >>> p.with_stem('lib')
      PureWindowsPath('c:/Downloads/lib.gz')
      >>> p = PureWindowsPath('c:/')
      >>> p.with_stem('')
      Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
        File "/home/antoine/cpython/default/Lib/pathlib.py", line 861, in with_stem
          return self.with_name(stem + self.suffix)
        File "/home/antoine/cpython/default/Lib/pathlib.py", line 851, in with_name
          raise ValueError("%r has an empty name" % (self,))
      ValueError: PureWindowsPath('c:/') has an empty name

   Added in version 3.9.

PurePath.with_suffix(suffix)

   "suffix" を変更した新しいパスを返します。 元のパスに suffix が無か
   った場合、代わりに新しい *suffix* が追加されます。 *suffix* が空文
   字列だった場合、元の suffix は除去されます:

      >>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
      >>> p.with_suffix('.bz2')
      PureWindowsPath('c:/Downloads/pathlib.tar.bz2')
      >>> p = PureWindowsPath('README')
      >>> p.with_suffix('.txt')
      PureWindowsPath('README.txt')
      >>> p = PureWindowsPath('README.txt')
      >>> p.with_suffix('')
      PureWindowsPath('README')

   バージョン 3.14 で変更: A single dot (""."") is considered a valid
   suffix. In previous versions, "ValueError" is raised if a single
   dot is supplied.

PurePath.with_segments(*pathsegments)

   Create a new path object of the same type by combining the given
   *pathsegments*. This method is called whenever a derivative path is
   created, such as from "parent" 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

   Added in version 3.12.


具象パス
========

具象パスは純粋パスクラスのサブクラスです。純粋パスが提供する操作に加え
、パスオブジェクト上でシステムコールを呼ぶメソッドも提供しています。具
象パスのインスタンスを作成するには 3 つの方法があります:

class pathlib.Path(*pathsegments)

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

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

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

class pathlib.PosixPath(*pathsegments)

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

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

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

   バージョン 3.13 で変更: Windows では "UnsupportedOperation" を送出
   します。以前のバージョンでは代わりに "NotImplementedError" を送出し
   ていました。

class pathlib.WindowsPath(*pathsegments)

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

      >>> WindowsPath('c:/', 'Users', 'Ximénez')
      WindowsPath('c:/Users/Ximénez')

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

   バージョン 3.13 で変更: Windows 以外のプラットフォームでは
   "UnsupportedOperation" を送出します。以前のバージョンでは代わりに
   "NotImplementedError" を送出していました。

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

   >>> import os
   >>> os.name
   'posix'
   >>> Path('setup.py')
   PosixPath('setup.py')
   >>> PosixPath('setup.py')
   PosixPath('setup.py')
   >>> WindowsPath('setup.py')
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
     File "pathlib.py", line 798, in __new__
       % (cls.__name__,))
   UnsupportedOperation: cannot instantiate 'WindowsPath' on your system

Some concrete path methods can raise an "OSError" if a system call
fails (for example because the path doesn't exist).


URIのパースと生成
-----------------

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)

   'file' URIをパースして新しいパスオブジェクトを返します。例:

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

   Added in version 3.13.

Path.as_uri()

   Represent the path as a 'file' URI.  "ValueError" is raised if the
   path isn't absolute.

      >>> p = PosixPath('/etc/passwd')
      >>> p.as_uri()
      'file:///etc/passwd'
      >>> p = WindowsPath('c:/Windows')
      >>> p.as_uri()
      'file:///c:/Windows'

   For historical reasons, this method is also available from
   "PurePath" objects. However, its use of "os.fsencode()" makes it
   strictly impure.


パスの展開と解決
----------------

classmethod Path.home()

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

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

   Added in version 3.5.

Path.expanduser()

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

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

   Added in version 3.5.

classmethod Path.cwd()

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

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

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

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

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

   Added in version 3.9.

   バージョン 3.13 で変更: "os.readlink()" が利用できない場合
   "UnsupportedOperation" を送出します。以前のバージョンでは
   "NotImplementedError" を送出していました。


ファイルの種類とステータスを問い合わせる
----------------------------------------

バージョン 3.8 で変更: "exists()", "is_dir()", "is_file()",
"is_mount()", "is_symlink()", "is_block_device()", "is_char_device()",
"is_fifo()", "is_socket()" now return "False" instead of raising an
exception for paths that contain characters unrepresentable at the OS
level.

バージョン 3.14 で変更: The methods given above now return "False"
instead of raising any "OSError" exception from the operating system.
In previous versions, some kinds of "OSError" exception are raised,
and others suppressed. The new behaviour is consistent with
"os.path.exists()", "os.path.isdir()", etc. Use "stat()" to retrieve
the file status without suppressing exceptions.

Path.stat(*, follow_symlinks=True)

   ("os.stat()" と同様の) 現在のパスについて "os.stat_result" オブジェ
   クトが含む情報を返します。値はそれぞれのメソッドを呼び出した時点の
   ものになります。

   このメソッドは通常はシンボリックリンクをたどります。シンボリックリ
   ンクに対して stat したい場合は "follow_symlinks=False" とするか、
   "lstat()" を利用してください。

      >>> p = Path('setup.py')
      >>> p.stat().st_size
      956
      >>> p.stat().st_mtime
      1327883547.852554

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

Path.lstat()

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

Path.exists(*, follow_symlinks=True)

   Return "True" if the path points to an existing file or directory.
   "False" will be returned if the path is invalid, inaccessible or
   missing. Use "Path.stat()" to distinguish between these cases.

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

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

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

Path.is_file(*, follow_symlinks=True)

   Return "True" if the path points to a regular file. "False" will be
   returned if the path is invalid, inaccessible or missing, or if it
   points to something other than a regular file. Use "Path.stat()" to
   distinguish between these cases.

   このメソッドは通常はシンボリックリンクをたどります。シンボリックリ
   ンクを除外するには "follow_symlinks=False" 引数を追加してください。

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

Path.is_dir(*, follow_symlinks=True)

   Return "True" if the path points to a directory. "False" will be
   returned if the path is invalid, inaccessible or missing, or if it
   points to something other than a directory. Use "Path.stat()" to
   distinguish between these cases.

   このメソッドは通常はシンボリックリンクをたどります。ディレクトリへ
   のシンボリックリンクを除外するには "follow_symlinks=False" 引数を追
   加してください。

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

Path.is_symlink()

   Return "True" if the path points to a symbolic link, even if that
   symlink is broken. "False" will be returned if the path is invalid,
   inaccessible or missing, or if it points to something other than a
   symbolic link. Use "Path.stat()" to distinguish between these
   cases.

Path.is_junction()

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

   Added in version 3.12.

Path.is_mount()

   パスがマウントポイント *mount point* (ファイルシステムの中で異なる
   ファイルシステムがマウントされているところ) なら、 "True" を返しま
   す。POSIX では、この関数は *path* の親ディレクトリである "path/.."
   が *path* と異なるデバイス上にあるか、あるいは "path/.." と *path*
   が同じデバイス上の同じ i-node を指しているかをチェックします --- こ
   れによって全ての Unix 系システムと POSIX 標準でマウントポイントが検
   出できます。Windowsでは、マウントポイントはドライブレターを持つルー
   ト(e.g. "c:\")、共有 UNC(e.g. "\\server\share")またはマウントされた
   ファイルシステムのディレクトリです。

   Added in version 3.7.

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

Path.is_socket()

   Return "True" if the path points to a Unix socket. "False" will be
   returned if the path is invalid, inaccessible or missing, or if it
   points to something other than a Unix socket. Use "Path.stat()" to
   distinguish between these cases.

Path.is_fifo()

   Return "True" if the path points to a FIFO. "False" will be
   returned if the path is invalid, inaccessible or missing, or if it
   points to something other than a FIFO. Use "Path.stat()" to
   distinguish between these cases.

Path.is_block_device()

   Return "True" if the path points to a block device. "False" will be
   returned if the path is invalid, inaccessible or missing, or if it
   points to something other than a block device. Use "Path.stat()" to
   distinguish between these cases.

Path.is_char_device()

   Return "True" if the path points to a character device. "False"
   will be returned if the path is invalid, inaccessible or missing,
   or if it points to something other than a character device. Use
   "Path.stat()" to distinguish between these cases.

Path.samefile(other_path)

   このパスが参照するファイルが *other_path* (Path オブジェクトか文字
   列) と同じであれば "True" を、異なるファイルであれば "False" を返し
   ます。意味的には "os.path.samefile()" および "os.path.samestat()"
   と同じです。

   なんらかの理由でどちらかのファイルにアクセスできない場合は
   "OSError" が送出されます。

      >>> p = Path('spam')
      >>> q = Path('eggs')
      >>> p.samefile(q)
      False
      >>> p.samefile('spam')
      True

   Added in version 3.5.


ファイルを読み書きする
----------------------

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

   組み込み関数 "open()" のようにパスが指しているファイルを開きます:

      >>> p = Path('setup.py')
      >>> with p.open() as f:
      ...     f.readline()
      ...
      '#!/usr/bin/env python3\n'

Path.read_text(encoding=None, errors=None, newline=None)

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

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

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

   Added in version 3.5.

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

Path.read_bytes()

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

      >>> p = Path('my_binary_file')
      >>> p.write_bytes(b'Binary file contents')
      20
      >>> p.read_bytes()
      b'Binary file contents'

   Added in version 3.5.

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

   指定されたファイルをテキストモードで開き、*data* を書き込み、ファイ
   ルを閉じます:

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

   同じ名前のファイルが存在する場合は上書きされます。オプションのパラ
   メーターの意味は "open()" と同じです。

   Added in version 3.5.

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

Path.write_bytes(data)

   指定されたファイルをバイトモードで開き、*data* を書き込み、ファイル
   を閉じます:

      >>> p = Path('my_binary_file')
      >>> p.write_bytes(b'Binary file contents')
      20
      >>> p.read_bytes()
      b'Binary file contents'

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

   Added in version 3.5.


ディレクトリを読む
------------------

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 されます。特殊なパスの "'.'" と "'..'"
   は含まれません。イテレーターを生成したあとにディレクトリにファイル
   を削除または追加した場合に、そのファイルのパスオブジェクトが含まれ
   るかは定義されていません。

   パスがディレクトリでないかアクセスできない場合は "OSError" を送出し
   ます。

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 ドキュメント。

   デフォルトまたは *case_sensitive* キーワード専用引数に "None" を指
   定した場合、このメソッドはパスの一致判定にプラットフォームに依存し
   た大文字小文字のルールを使用します。一般的にPOSIXは大文字と小文字を
   区別し、Windowsは区別しません。*case_sensitive* を "True" または
   "False" に設定するとこの動作を上書きします。

   デフォルトまたは  *recurse_symlinks* キーワード専用引数が "False"
   に設定された場合、このメソッドは ""**"" ワイルドカードの展開時にシ
   ンボリックリンクをたどりません。*recurse_symlinks* を "True" に設定
   すると、つねにシンボリックリンクをたどります。

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

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

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

   バージョン 3.13 で変更: *pattern* パラメタが *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)

   与えられた相対  *pattern* で再帰的に Glob します。"Path.glob()" で
   *pattern* の前に ""**/"" をつけ呼び出した場合と似ています。

   参考: Pattern language と "Path.glob()" のドキュメント。

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

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

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

   バージョン 3.13 で変更: *pattern* パラメタが *path-like object* を
   受け付けるようになりました。

Path.walk(top_down=True, on_error=None, follow_symlinks=False)

   Generate the file names in a directory tree by walking the tree
   either top-down or bottom-up.

   For each directory in the directory tree rooted at *self*
   (including *self* but excluding '.' and '..'), the method yields a
   3-tuple of "(dirpath, dirnames, filenames)".

   *dirpath* is a "Path" to the directory currently being walked,
   *dirnames* is a list of strings for the names of subdirectories in
   *dirpath* (excluding "'.'" and "'..'"), and *filenames* is a list
   of strings for the names of the non-directory files in *dirpath*.
   To get a full path (which begins with *self*) to a file or
   directory in *dirpath*, 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()

   Added in version 3.12.


ファイルとディレクトリの作成
----------------------------

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

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

   参考:

     The "open()", "write_text()" and "write_bytes()" methods are
     often used to create files.

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.symlink_to(target, target_is_directory=False)

   Make this path a symbolic link pointing to *target*.

   Windows では、シンボリックリンクはファイルかディレクトリのどちらか
   を表しますが、ターゲットに合わせて動的に変化することはありません。
   ターゲットが存在する場合、シンボリックリンクの種類は対象に合わせて
   作成されます。ターゲットが存在せず *target_is_directory* が真である
   場合、シンボリックリンクはディレクトリのリンクとして作成され、偽で
   ある場合 (デフォルト) はファイルのリンクになります。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 で変更: "os.symlink()" が利用できない場合
   "UnsupportedOperation" を送出します。以前のバージョンでは
   "NotImplementedError" を送出していました。

Path.hardlink_to(target)

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

   注釈:

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

   Added in version 3.10.

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


Copying, moving and deleting
----------------------------

Path.copy(target, *, follow_symlinks=True, dirs_exist_ok=False, preserve_metadata=False)

   Copy this file or directory tree to the given *target*, and return
   a new "Path" instance pointing to *target*.

   If the source is a file, the target will be replaced if it is an
   existing file. If the source is a symlink and *follow_symlinks* is
   true (the default), the symlink's target is copied. Otherwise, the
   symlink is recreated at the destination.

   If the source is a directory and *dirs_exist_ok* is false (the
   default), a "FileExistsError" is raised if the target is an
   existing directory. If *dirs_exists_ok* is true, the copying
   operation will overwrite existing files within the destination tree
   with corresponding files from the source tree.

   If *preserve_metadata* is false (the default), only directory
   structures and file data are guaranteed to be copied. Set
   *preserve_metadata* to true to ensure that file and directory
   permissions, flags, last access and modification times, and
   extended attributes are copied where supported. This argument has
   no effect when copying files on Windows (where metadata is always
   preserved).

   Added in version 3.14.

Path.copy_into(target_dir, *, follow_symlinks=True, dirs_exist_ok=False, preserve_metadata=False)

   Copy this file or directory tree into the given *target_dir*, which
   should be an existing directory. Other arguments are handled
   identically to "Path.copy()". Returns a new "Path" instance
   pointing to the copy.

   Added in version 3.14.

Path.rename(target)

   このファイルかディレクトリを与えられた *target* にリネームし、
   *target* を指す新しい "Path" のインスタンスを返します。 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* を指す新しい "Path" のインスタンスを返します。*target* が
   既存のファイルか空のディレクトリを指していた場合、無条件に置き換え
   られます。

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

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

Path.move(target)

   Move this file or directory tree to the given *target*, and return
   a new "Path" instance pointing to *target*.

   If the *target* doesn't exist it will be created. If both this path
   and the *target* are existing files, then the target is
   overwritten. If both paths point to the same file or directory, or
   the *target* is a non-empty directory, then "OSError" is raised.

   If both paths are on the same filesystem, the move is performed
   with "os.replace()". Otherwise, this path is copied (preserving
   metadata and symlinks) and then deleted.

   Added in version 3.14.

Path.move_into(target_dir)

   Move this file or directory tree into the given *target_dir*, which
   should be an existing directory. Returns a new "Path" instance
   pointing to the moved path.

   Added in version 3.14.

Path.unlink(missing_ok=False)

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

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

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

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

Path.rmdir()

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


パーミッションと所有者
----------------------

Path.owner(*, follow_symlinks=True)

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

   このメソッドは通常はシンボリックリンクをたどります。シンボリックリ
   ンクの所有者を取得するには "follow_symlinks=False" 引数を追加してく
   ださい。

   バージョン 3.13 で変更: "pwd" モジュールが利用できない場合
   "UnsupportedOperation" を送出します。以前のバージョンでは
   "NotImplementedError" を送出していました。

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

Path.group(*, follow_symlinks=True)

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

   このメソッドは通常はシンボリックリンクをたどります。シンボリックリ
   ンクのグループを取得するには "follow_symlinks=False" 引数を追加して
   ください。

   バージョン 3.13 で変更: "grp" モジュールが利用できない場合
   "UnsupportedOperation" を送出します。以前のバージョンでは
   "NotImplementedError" を送出していました。

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

Path.chmod(mode, *, follow_symlinks=True)

   "os.chmod()" のようにファイルのモードとアクセス権限を変更します。

   このメソッドは通常シンボリックリンクをたどります。一部のUnixではシ
   ンボリックリンク自体のパーミッション変更をサポートしています。その
   ようなプラットフォームでは引数に``follow_symlinks=False`` を追加す
   るか、"lchmod()" を使用してください。

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

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

Path.lchmod(mode)

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


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                   | 意味                                                                  |
|===========================|=======================================================================|
| ""**/*""                  | 1つ以上の要素がある任意のパス。                                       |
+---------------------------+-----------------------------------------------------------------------+
| ""**/*.py""               | 最後の要素が "".py"" で終わる任意のパス。                             |
+---------------------------+-----------------------------------------------------------------------+
| ""assets/**""             | ""assets/"" で始まる任意のパス。                                      |
+---------------------------+-----------------------------------------------------------------------+
| ""assets/**/*""           | ""assets/"" で始まる任意のパス(""assets/"" 自身を除く)。              |
+---------------------------+-----------------------------------------------------------------------+

注釈:

  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.


"glob" モジュールとの比較
=========================

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


"os" と "os.path" モジュールの比較
==================================

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


対応するツール
--------------

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

+---------------------------------------+------------------------------------------------+
| "os" と "os.path"                     | "pathlib"                                      |
|=======================================|================================================|
| "os.path.dirname()"                   | "PurePath.parent"                              |
+---------------------------------------+------------------------------------------------+
| "os.path.basename()"                  | "PurePath.name"                                |
+---------------------------------------+------------------------------------------------+
| "os.path.splitext()"                  | "PurePath.stem", "PurePath.suffix"             |
+---------------------------------------+------------------------------------------------+
| "os.path.join()"                      | "PurePath.joinpath()"                          |
+---------------------------------------+------------------------------------------------+
| "os.path.isabs()"                     | "PurePath.is_absolute()"                       |
+---------------------------------------+------------------------------------------------+
| "os.path.relpath()"                   | "PurePath.relative_to()" [1]                   |
+---------------------------------------+------------------------------------------------+
| "os.path.expanduser()"                | "Path.expanduser()" [2]                        |
+---------------------------------------+------------------------------------------------+
| "os.path.realpath()"                  | "Path.resolve()"                               |
+---------------------------------------+------------------------------------------------+
| "os.path.abspath()"                   | "Path.absolute()" [3]                          |
+---------------------------------------+------------------------------------------------+
| "os.path.exists()"                    | "Path.exists()"                                |
+---------------------------------------+------------------------------------------------+
| "os.path.isfile()"                    | "Path.is_file()"                               |
+---------------------------------------+------------------------------------------------+
| "os.path.isdir()"                     | "Path.is_dir()"                                |
+---------------------------------------+------------------------------------------------+
| "os.path.islink()"                    | "Path.is_symlink()"                            |
+---------------------------------------+------------------------------------------------+
| "os.path.isjunction()"                | "Path.is_junction()"                           |
+---------------------------------------+------------------------------------------------+
| "os.path.ismount()"                   | "Path.is_mount()"                              |
+---------------------------------------+------------------------------------------------+
| "os.path.samefile()"                  | "Path.samefile()"                              |
+---------------------------------------+------------------------------------------------+
| "os.getcwd()"                         | "Path.cwd()"                                   |
+---------------------------------------+------------------------------------------------+
| "os.stat()"                           | "Path.stat()"                                  |
+---------------------------------------+------------------------------------------------+
| "os.lstat()"                          | "Path.lstat()"                                 |
+---------------------------------------+------------------------------------------------+
| "os.listdir()"                        | "Path.iterdir()"                               |
+---------------------------------------+------------------------------------------------+
| "os.walk()"                           | "Path.walk()" [4]                              |
+---------------------------------------+------------------------------------------------+
| "os.mkdir()", "os.makedirs()"         | "Path.mkdir()"                                 |
+---------------------------------------+------------------------------------------------+
| "os.link()"                           | "Path.hardlink_to()"                           |
+---------------------------------------+------------------------------------------------+
| "os.symlink()"                        | "Path.symlink_to()"                            |
+---------------------------------------+------------------------------------------------+
| "os.readlink()"                       | "Path.readlink()"                              |
+---------------------------------------+------------------------------------------------+
| "os.rename()"                         | "Path.rename()"                                |
+---------------------------------------+------------------------------------------------+
| "os.replace()"                        | "Path.replace()"                               |
+---------------------------------------+------------------------------------------------+
| "os.remove()", "os.unlink()"          | "Path.unlink()"                                |
+---------------------------------------+------------------------------------------------+
| "os.rmdir()"                          | "Path.rmdir()"                                 |
+---------------------------------------+------------------------------------------------+
| "os.chmod()"                          | "Path.chmod()"                                 |
+---------------------------------------+------------------------------------------------+
| "os.lchmod()"                         | "Path.lchmod()"                                |
+---------------------------------------+------------------------------------------------+

-[ 脚注 ]-

[1] "os.path.relpath()" calls "abspath()" to make paths absolute and
    remove "".."" parts, whereas "PurePath.relative_to()" is a lexical
    operation that raises "ValueError" when its inputs' anchors differ
    (e.g. if one path is absolute and the other relative.)

[2] "os.path.expanduser()" returns the path unchanged if the home
    directory can't be resolved, whereas "Path.expanduser()" raises
    "RuntimeError".

[3] "os.path.abspath()" removes "".."" components without resolving
    symlinks, which may change the meaning of the path, whereas
    "Path.absolute()" leaves any "".."" components in the path.

[4] "os.walk()" always follows symlinks when categorizing paths into
    *dirnames* and *filenames*, whereas "Path.walk()" categorizes all
    symlinks into *filenames* when *follow_symlinks* is false (the
    default.)
