Pythonの標準ライブラリであるpathlib
は、ファイルパスを扱うためのライブラリです。pathlib
を使うと、ファイルパスを文字列で扱うのではなく、オブジェクトとして扱うことができます。
pathlibのメリット
pathlib
は、os.path
と比べて、次のようなメリットがあります。
- 豊富なメソッド: ファイルパスをオブジェクトとして扱うので、ファイルパスに対して様々な操作を行うことができます。
- パスの区切り文字の違いを吸収: OSによって異なるパスの区切り文字を吸収してくれます。
- パスの結合が簡単:
/
演算子を使ってパスを結合することができます。
pathlibの基本的な使い方
以下に、pathlib
の基本的な使い方を示します。
パスの生成
from pathlib import Path
# 絶対パス
path = Path("/home/user/test.txt")
# 並べて書くと、結合される
path = Path("/home", "user", "test.txt") # /home/user/test.txt
# 相対パス
path = Path("test.txt")
# 現在のディレクトリ
path = Path.cwd()
パスの結合
from pathlib import Path
# Pathオブジェクト + Pathオブジェクト
path = Path("/home/user") / Path("test.txt")
# Pathオブジェクト + 文字列
path = Path("/home/user") / "test.txt"
# joinpathメソッド
path = Path("/home/user").joinpath("test.txt")
# 結合結果
print(path) # /home/user/test.txt
パスの分解
from pathlib import Path
path = Path("/home/user/test.txt")
# ディレクトリ名
print(path.parent) # /home/user
# ファイル名と拡張子
print(path.name) # test.txt
# ファイル名(拡張子なし)
print(path.stem) # test
# 拡張子
print(path.suffix) # .txt
パスの存在確認
from pathlib import Path
path = Path("/home/user/test.txt")
# パスが存在するか
print(path.exists()) # True
# パスがファイルか
print(path.is_file()) # True
# パスがディレクトリか
print(path.is_dir()) # False
相対パスと絶対パスの変換
from pathlib import Path
# 絶対パス
abspath = Path("/home/user/test.txt")
# 相対パス化
print(abspath.relative_to("/home")) # user/test.txt
# 相対パス
relpath = Path("user/test.txt")
# 絶対パス化
print(relpath.absolute()) # /home/user/test.txt
# ..や.を含むパスを解決する
print(Path("user/../test.txt").resolve()) # /home/test.txt
以上が、Pythonのpathlib
を用いたパス操作の基本的な使い方です。これらの操作を駆使することで、ファイルやディレクトリのパス操作を効率的に行うことができます。