Python | pathlib を使って画像ファイルを扱う実践例

Python
スポンサーリンク

では pathlib を使って画像ファイルを扱う実践例 を、初心者向けに分かりやすく紹介します。ここでは「画像ファイルの存在確認」「コピー」「フォルダ内の画像一覧取得」など、よくある操作を例題にします。


1. 画像ファイルの存在確認

from pathlib import Path

# 画像ファイルのパスを指定
img_path = Path.home() / "Pictures" / "sample.png"

# 存在確認
if img_path.exists():
    print("画像が見つかりました:", img_path)
else:
    print("画像が存在しません")
Python

👉 Path.exists() でファイルの有無を簡単に確認できます。


2. 画像ファイルのコピー

from pathlib import Path
import shutil

src = Path.home() / "Pictures" / "sample.png"
dst = Path.home() / "Desktop" / "backup_sample.png"

if src.exists():
    shutil.copy(src, dst)
    print("コピーしました:", dst)
Python

👉 shutil.copy() を使えば、Path オブジェクトをそのまま渡してコピー可能。


3. フォルダ内の画像一覧を取得

from pathlib import Path

img_dir = Path.home() / "Pictures"

# jpg と png を探す
for img in img_dir.glob("*.jpg"):
    print("JPG:", img)

for img in img_dir.glob("*.png"):
    print("PNG:", img)
Python

👉 glob("*.拡張子") で特定の形式のファイルを検索できます。


4. 実践例:画像をまとめて別フォルダに移動

from pathlib import Path
import shutil

src_dir = Path.home() / "Downloads"
dst_dir = Path.home() / "Pictures" / "整理済み"

# 保存先フォルダを作成(なければ作る)
dst_dir.mkdir(exist_ok=True)

# jpg と png をまとめて移動
for img in src_dir.glob("*.jpg"):
    shutil.move(img, dst_dir / img.name)

for img in src_dir.glob("*.png"):
    shutil.move(img, dst_dir / img.name)

print("画像を整理しました:", dst_dir)
Python

👉 ダウンロードフォルダに散らばった画像を一括整理できます。


5. さらに応用(Pillowと組み合わせ)

pathlib は画像処理ライブラリ Pillow とも相性抜群です。

from pathlib import Path
from PIL import Image

img_path = Path.home() / "Pictures" / "sample.png"

if img_path.exists():
    img = Image.open(img_path)
    print("サイズ:", img.size)
    print("形式:", img.format)

    # サムネイルを作成して保存
    img.thumbnail((200, 200))
    thumb_path = img_path.with_name("sample_thumb.png")
    img.save(thumb_path)
    print("サムネイルを保存しました:", thumb_path)
Python

👉 pathlib でパスを管理しつつ、Pillowで画像処理ができます。


まとめ

  • pathlib で画像ファイルの 存在確認・コピー・移動・検索 が簡単にできる
  • glob() を使えば拡張子ごとに画像を探せる
  • Pillowと組み合わせると 画像のサイズ取得や変換 もスムーズ

次のステップとしては、「pathlib + Pillow」でフォルダ内の画像を一括リサイズするスクリプトを作ると、実用的で面白いですよ。

Python
スポンサーリンク
シェアする
@lifehackerをフォローする
スポンサーリンク
タイトルとURLをコピーしました