Pythonのpathlib逆引き辞典

Python

逆引きpathlib辞典

個人メモを兼ねて「pathlibでこう使いたい!」というケースごとにコードを置いておきます。

公式ドキュメント

ファイル名(拡張子を除く)を取得したい

Path.stemで取得できます

# sample.py
from pathlib import Path
current_file = Path(__file__)
print(current_file.stem) # >>> "sample"

拡張子を取得したい

Path.suffixで取得できます

# sample.py
from pathlib import Path
current_file = Path(__file__)
print(current_file.suffix) # >>> ".py"

ファイルのディレクトリを取得したい

# scratch/sample.py
from pathlib import Path
current_file = Path(__file__)
print(current_file.parent) # >>> "scratch"

ディレクトリを追加したい

/演算子でディレクトリを追加できます。おしゃれですね

from pathlib import Path
current_file = Path(__file__)
current_folder = current_file.parent
new_folder = current_folder / "new"

文字列に変換したい

strで行えます。メソッドで用意されていると嬉しいですが…

from pathlib import Path
current_file = Path(__file__)
print(str(current_file)) # >> "C:\\hoge\\sample.py"

コメント

タイトルとURLをコピーしました