Code
from IPython import InteractiveShell
= 'all'
InteractiveShell.ast_node_interactivity
import session_info
September 25, 2024
Python3でファイル・ディレクトリ操作を行う方法をまとめる。
pathlib
modulepathlib
モジュールはPython 3.4から導入され、ファイルシステムのパスを操作する機能を提供する。 主要な機能を提供するPath
サブクラスをimport
して使用する。
PosixPath
クラスの属性PosixPath
クラスの属性にアクセスすることで、パスの特定の部分文字列を抽出することができる。
### `name`属性
# パスのbasename(パスの末尾の要素)
p.name
#> 'file.txt.gz'
### `suffix`, `suffixes`属性
# file suffix(ファイル拡張子)
p.suffix
#> '.gz'
p.suffixes
#> ['.txt', '.gz']
### `stem`属性
# パスのstem(basename - file suffix)
p.stem
#> 'file.txt'
### `parent`, `parents`属性
# parent属性でディレクトリのパス、parents属性とインデックスで一気に上位のディレクトリのパス
p.parent
#> PosixPath('path/to')
p.parents[0]
#> PosixPath('path/to')
p.parents[1]
#> PosixPath('path')
### `parts`属性
# パスを構成する要素からなるタプル
p.parts
#> ('path', 'to', 'file.txt.gz')
with_*()
メソッドでファイル名(パスの最後の要素)を変更することができる。
Path.glob()
メソッドで指定したディレクトリ内のパスを返すジェネレータを得ることができる。
Path
のクラスメソッド
p = Path("test/scripts/../scripts/../not_exist/script.py")
# absolute()は絶対パスに字句解析的に変換
p.absolute().relative_to(Path.cwd())
#> PosixPath('test/scripts/../scripts/../not_exist/script.py')
# resolve()は途中の`..`などを解消する
p.resolve().relative_to(Path.cwd())
#> PosixPath('test/not_exist/script.py')
# strict=Trueを指定すると、存在しない場合はエラーを返す
p.resolve(strict=True)
#> FileNotFoundError: [Errno 2] No such file or directory: 'test/not_exist'
shutil
modulepathlib
モジュールでは行いにくい一部の操作については、標準ライブラリのshutil
モジュールなどを使うとよい。
pathlib
モジュールでもファイルやディレクトリを削除するメソッドが用意されている。 しかし、やや使い勝手が悪くファイルをディレクトリごと削除したい場合などに不便である。
# ファイルの削除はunlink()メソッドで行う
Path("test/script.py").unlink()
# ファイルが存在しない場合はエラー(missing_ok引数をTrueに設定するとエラーを出さない)
Path("not_exist.txt").unlink(missing_ok=False)
#> FileNotFoundError: [Errno 2] No such file or directory: 'not_exist.txt'
# ディレクトリの削除はrmdir()メソッドで行うが、空ディレクトリ出なければ削除できない。
Path("test/").rmdir()
#> OSError: [Errno 66] Directory not empty: 'test'
フォルダごとファイルを削除するにはshutil.rmtree()
関数を用いる。