2021-07-29に投稿

Python 標準ライブラリ pathlib ファイルシステムパス

Pythonの標準にあるファイルシステムパスの操作を行えるライブラリpathlibの解説です。

概要

文字としてのファイルパスで使えるPureなクラスと、
I/O操作を含むクラスが用意されている。

graph BT
    PurePosixPath --> PurePath
    Path --> PurePath
    PureWindowsPath --> PurePath
    PosixPath --> PurePosixPath
    PosixPath --> Path
    WindowsPath --> PureWindowsPath
    WindowsPath --> Path

コンストラクタ(Pure)

Pathのインスタンスは、パスを構成する文字列を1つ以上渡して作成できる。
(以降例はWindows環境)

### PurePath(*pathsegments)
pathlib.PurePath() # => PureWindowsPath('.')
pathlib.PurePath('') # => PureWindowsPath('.')
pathlib.PurePath('sample1.py') # => PureWindowsPath('sample1.py')
pathlib.PurePath('subdir1','sampleA.py') # => PureWindowsPath('subdir1/sampleA.py')
pathlib.PurePath('/etc','path','sampleA.py') # => PureWindowsPath('/etc/path/sampleA.py')

pathlib.PurePath(pathlib.PurePath('subdir1'),pathlib.Path('subdir2')) # => PureWindowsPath('subdir1/subdir2')
pathlib.PurePath('C:\\Program Files', 'Python') # => PureWindowsPath('C:/Program Files/Python')
pathlib.PurePath('D:\\','Program Files', 'Python') # => PureWindowsPath('D:/Program Files/Python')

PurePathを使うと環境に応じてPurePosixPathまたはPureWindowsPathが自動で作成される。
以下のように明示的に作成を行う事も可能。

### PurePosixPath(*pathsegments)
pathlib.PurePosixPath('/etc','path','sampleA.py') # => PurePosixPath('/etc/path/sampleA.py')

### PureWindowsPath(*pathsegments)
pathlib.PureWindowsPath('C:\\','path','sampleA.py') # => PureWindowsPath('C:/path/sampleA.py')

メソッドとプロパティ(Pure)

p = pathlib.PurePath('C:\\','path','sub','sampleA.py') # => PureWindowsPath('C:/path/sub/sampleA.py')

### parts 構成要素
p.parts # => ('C:\\', 'path', 'sub', 'sampleA.py')

### drive ドライブ
p.drive # => 'C:'

### anchor ドライブとルート
p.anchor # => 'C:\\'

### parents 親達のパスのシーケンス
list(p.parents) # => [PureWindowsPath('C:/path/sub'), PureWindowsPath('C:/path'), PureWindowsPath('C:/')]

### parent 直上の親のパス
p.parent #=> PureWindowsPath('C:/path/sub')

### name 末尾のファイル、ディレクトリの名称
p.name # => 'sampleA.py'

### suffix 拡張子
p.suffix # => '.py'
pathlib.PurePath('sample.tar.gz').suffix # => '.gz'

### suffixes 拡張子(複数)
p.suffixes # => ['.py']
pathlib.PurePath('sample.tar.gz').suffixes # => ['.tar', '.gz']

### stem 拡張子を除外した名称
p.stem  # => 'sampleA'
pathlib.PurePath('sample.tar.gz').stem # => 'sample.tar'

### as_posix() スラッシュのパス文字列
p.as_posix()  # => 'C:/path/sub/sampleA.py'

### as_uri() スキーマfile://のパス
p.as_uri()  # => 'file:///C:/path/sub/sampleA.py'

### is_absolute()  絶対パスであるかの判定
p.is_absolute() # => True
pathlib.PurePath('sample1.py').is_absolute() # => False

### is_relative_to(*other) 相対パスであるか
#=> PureWindowsPath('C:/path/sub/sampleA.py')
p.is_relative_to('C:\\path') # => True
p.is_relative_to('C:\\path\\sub') # => True
p.is_relative_to('C:\\pathmore') # => False

### joinpath(*other) パスの結合
pathlib.PurePath('C:\\','path').joinpath('sub').joinpath('sampleA.py')
# => PureWindowsPath('C:/path/sub/sampleA.py')

### match(pattern) パスがマッチするか
p.match('*.py') # => True
p.match('sub/*.py') # => True
p.match('path/*.py') # => False
p.match('path/*/*.py') # => True
p.match('C://path/*/*.py') # => True
p.match('C://path/sub/*.*') # => True
p.match('sub\\*.py') # => True

### relative_to(*other) 指定パスからの相対パス
p.relative_to('C:\\') # => PureWindowsPath('path/sub/sampleA.py')
p.relative_to('C:\\path') # => PureWindowsPath('sub/sampleA.py')
p.relative_to('C:\\path\\sub') # => PureWindowsPath('sampleA.py')

### with_name(name)  ファイル名を変更したパス
p.with_name('somefilename.py') # => PureWindowsPath('C:/path/sub/somefilename.py')
pathlib.PurePath('sample.tar.gz').with_name('test.tar.gz') # => PureWindowsPath('test.tar.gz')

### with_stem(name) 拡張子を除いたファイル名を変更したパス
p.with_stem('somefilename') # => PureWindowsPath('C:/path/sub/somefilename.py')
pathlib.PurePath('sample.tar.gz').with_stem('test.tar') # => PureWindowsPath('test.tar.gz')

### with_suffix(suffix) 拡張子変更
p.with_suffix('.txt') # => PureWindowsPath('C:/path/sub/sampleA.txt')
pathlib.PurePath('sample.tar.gz').with_suffix('.zip') # => PureWindowsPath('test.tar.zip')
pathlib.PurePath('sample').with_suffix('.log') # => PureWindowsPath('sample.log')

コンストラクタ(I/Oサポート、具象)

### Path(*pathsegments)
pathlib.Path('C:\\Program Files') # => WindowsPath('C:/Program Files')

### WindowsPath(*pathsegments)
pathlib.WindowsPath('C:\\Program Files') # => WindowsPath('C:/Program Files')

### PosixPath(*pathsegments)
pathlib.PosixPath('/etc') # => NotImplementedError: cannot instantiate 'PosixPath' on your system

メソッドとプロパティ(I/Oサポート、具象)

### Path.cwd() カレントディレクトリのパス
pathlib.Path.cwd() # => WindowsPath('c:/jupyter/path')

### Path.cwd() カレントディレクトリのパス
pathlib.Path.home() # => WindowsPath('C:/Users/username')

### stat() ファイル・ディレクトリ情報
pathlib.Path('C:\\Program Files').stat()

### exists() 存在チェック
pathlib.Path('C:\\Program Files').exists()

### expanduser() パスの展開
pathlib.Path('~/').expanduser()

### glob(pattern) マッチするファイル・ディレクトリのパス
list(pathlib.Path(r'C:\Users\username\Pictures\').glob('*.jpg'))

### rglob(pattern) **/を付与して配下を検索
list(pathlib.Path("./test/").rglob("*.txt"))

### is_dir() ディレクトリ判定
pathlib.Path('C:\\Program Files').is_dir()

### is_file() ファイル判定
pathlib.Path('C:\\Program Files').is_file()

### iterdir() 配下ディレクトリのイテレータ
list(pathlib.Path('C:\\Program Files').iterdir())

### mkdir() ディレクトリ作成
pathlib.Path("./test/").mkdir()

### rmdir() ディレクトリ削除
pathlib.Path("./test/").rmdir()

### touch() ファイル作成
pathlib.Path("./test/sample.txt").touch()

### unlink() ファイル削除
pathlib.Path("./test/sample.txt").unlink()

### write_text(data, encoding=None, errors=None) 文字列書き込み
pathlib.Path("./test/sample.txt").write_text("あいうえお",encoding='utf8')

### read_text(encoding=None, errors=None) 文字列読み込み
pathlib.Path("./test/sample.txt").read_text(encoding='utf8')

### write_bytes(data) バイナリ書き込み
pathlib.Path("./test/sample.txt").write_bytes(b'abcde')

### read_bytes() バイナリ読み込み
pathlib.Path("./test/sample.txt").read_bytes()

### rename(target) リネーム
pathlib.Path("./test/sample2.txt").rename("./test/sample3.txt")

### replace(target) 置き換え
pathlib.Path("./test/sample.txt").replace("./test/sample2.txt")
Originally published at marusankakusikaku.jp
ツイッターでシェア
みんなに共有、忘れないようにメモ

maru3kaku4kaku

Pythonこつこつ学習中。よく忘れる。

Crieitは誰でも投稿できるサービスです。 是非記事の投稿をお願いします。どんな軽い内容でも投稿できます。

また、「こんな記事が読みたいけど見つからない!」という方は是非記事投稿リクエストボードへ!

有料記事を販売できるようになりました!

こじんまりと作業ログやメモ、進捗を書き残しておきたい方はボード機能をご利用ください。
ボードとは?

コメント