3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python標準ライブラリの掘り下げ:pathlibによるファイル操作のモダン化

Posted at

概要

ファイル操作といえば、かつては osos.pathglob などを組み合わせて記述するのが定石だった。
しかし Python 3.4 以降、オブジェクト指向的にパスを扱う pathlib モジュール が登場し、
ファイル操作のコードはより直感的かつモダンに進化した。

本稿では、pathlib.Path を中心としたファイル操作の現代的なスタイルを、
従来の手法との比較と実務的パターンを交えて解説する。


1. 基本:Pathオブジェクトの生成と操作

from pathlib import Path

p = Path("data") / "subdir" / "file.txt"
print(p)  # data/subdir/file.txt
  • / 演算子によって直感的にパス結合
  • Path オブジェクト自体がファイル/ディレクトリを表現する

2. パス情報の取得

p = Path("data/file.txt")

p.name         # 'file.txt'
p.stem         # 'file'
p.suffix       # '.txt'
p.parent       # Path('data')
p.exists()     # ファイル/ディレクトリの存在確認
p.is_file()    # ファイルか?
p.is_dir()     # ディレクトリか?

可読性の高いAPIで、os.path による分岐処理を簡潔化


3. ファイル・ディレクトリ操作

p = Path("output/log.txt")
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text("ログを出力します")
text = p.read_text()
  • mkdir(): 階層付きディレクトリ作成
  • write_text() / read_text(): テキストファイルの書き込み・読み込み
  • write_bytes() / read_bytes(): バイナリ対応

4. パターン検索とフィルタリング

for txt_file in Path("data").glob("**/*.txt"):
    print(txt_file.name)
  • glob() はワイルドカード検索
  • ** を使えば再帰的なディレクトリ探索も可能
  • iterdir() を使えば1階層のみの列挙もできる

5. パスの比較と正規化

a = Path("data/../data/file.txt")
b = Path("data/file.txt")

print(a.resolve() == b.resolve())  # True

resolve() を使うことで 実体のパスを取得して比較可能


6. 実務におけるベストパターン

✅ ディレクトリ構造の自動生成

base = Path("project/logs")
(base / "error").mkdir(parents=True, exist_ok=True)
(base / "access").mkdir(parents=True, exist_ok=True)

✅ ログのプレフィックス付きファイル名生成

from datetime import datetime

log_dir = Path("logs")
log_file = log_dir / f"log_{datetime.now():%Y%m%d}.txt"
log_file.write_text("起動しました。")

✅ 拡張子フィルタリング処理

images = [f for f in Path("assets").iterdir() if f.suffix in [".png", ".jpg"]]

if文とPathオブジェクトのメソッドを組み合わせることで簡潔に書ける


7. 従来構文との比較:os vs pathlib

操作 os.path pathlib.Path
パス結合 os.path.join(a, b) Path(a) / b
存在確認 os.path.exists(p) p.exists()
ディレクトリ作成 os.makedirs(p, exist_ok=True) p.mkdir(parents=True, exist_ok=True)
ファイル読み込み open(p).read() p.read_text()

pathlib によって 冗長な構文が大幅に削減される


よくある誤解と対策

❌ Pathオブジェクトはstrで使えない?

→ ✅ Pathstr() で文字列化可能、必要に応じて渡せる
→ 多くの関数は os.PathLike に対応しており Path をそのまま渡せる


❌ pathlibは高機能だが遅い?

→ ✅ 実質的なパフォーマンス差はほぼゼロ
→ メリットは 可読性・記述量・保守性の向上 にある


❌ Python2では使えない?

→ ✅ pathlib は Python 3.4+ 専用。レガシー環境では pathlib2 パッケージが代替


結語

pathlib は、Pythonのファイル操作を命令型から構造的なオブジェクト操作へ昇華させたライブラリである。

  • パスはただの文字列ではなく、操作対象としての抽象オブジェクト
  • 明快なAPIと柔軟な組み合わせにより、実務コードの安全性と可読性が大幅に向上
  • Pythonicな設計とは、“動作よりも構造を表現すること”であり、
    pathlib はまさにそれをファイル操作領域で体現している。
3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?