0
0

【Python】Pathlibモジュールの実践応用ガイド

Posted at

はじめに

前回の記事では、Pythonのpathlibモジュールの基本的な使い方について紹介しました。
今回は、その続編として、実際のプロジェクトでpathlibをどのように活用できるかを具体的な例を交えて紹介します。

・前回の記事

プロジェクトでのファイル操作の自動化

大規模なプロジェクトでは、ファイル操作を効率化するために自動化が重要です。
ここでは、pathlibを使ったファイルのバックアップスクリプトを紹介します。

from pathlib import Path
import shutil
import datetime

def backup_files(source_dir, backup_dir):
    # 現在の日付と時刻を取得
    now = datetime.datetime.now()
    backup_subdir = backup_dir / f"backup_{now.strftime('%Y%m%d_%H%M%S')}"
    
    # バックアップディレクトリを作成
    backup_subdir.mkdir(parents=True, exist_ok=True)
    
    # ソースディレクトリ内のすべてのファイルをバックアップ
    for item in source_dir.iterdir():
        if item.is_file():
            shutil.copy(item, backup_subdir / item.name)
            print(f"バックアップ: {item} -> {backup_subdir / item.name}")

# 使用例
source_dir = Path('/path/to/source')
backup_dir = Path('/path/to/backup')
backup_files(source_dir, backup_dir)

このスクリプトは、指定したソースディレクトリ内のすべてのファイルをバックアップディレクトリにコピーします。バックアップディレクトリには、日付と時刻を含むサブディレクトリが作成されます。

ログファイルの整理

プロジェクトでは、ログファイルが大量に生成されることがあります。これらのログファイルを整理するために、古いログファイルをアーカイブするスクリプトを紹介します。

import zipfile

def archive_old_logs(log_dir, archive_dir, days_old):
    # 現在の日付と時刻を取得
    now = datetime.datetime.now()
    
    # 古いログファイルをアーカイブ
    for log_file in log_dir.glob('*.log'):
        file_age = now - datetime.datetime.fromtimestamp(log_file.stat().st_mtime)
        if file_age.days > days_old:
            archive_path = archive_dir / f"{log_file.stem}.zip"
            with zipfile.ZipFile(archive_path, 'w') as zipf:
                zipf.write(log_file, arcname=log_file.name)
            log_file.unlink()
            print(f"アーカイブ: {log_file} -> {archive_path}")

# 使用例
log_dir = Path('/path/to/logs')
archive_dir = Path('/path/to/archive')
archive_old_logs(log_dir, archive_dir, days_old=30)

このスクリプトは、指定した日数より古いログファイルをZIPアーカイブにまとめ、元のログファイルを削除します。

プロジェクト構成のチェック

大規模なプロジェクトでは、ディレクトリ構成が複雑になることがあります。
ここでは、pathlibを使ってプロジェクトのディレクトリ構成をチェックするスクリプトを紹介します。

def check_project_structure(base_dir, expected_structure):
    for path, is_dir in expected_structure.items():
        target_path = base_dir / path
        if is_dir:
            if not target_path.is_dir():
                print(f"Missing directory: {target_path}")
        else:
            if not target_path.is_file():
                print(f"Missing file: {target_path}")

# 使用例
base_dir = Path('/path/to/project')
expected_structure = {
    'src': True,
    'src/main.py': False,
    'tests': True,
    'README.md': False
}
check_project_structure(base_dir, expected_structure)

このスクリプトは、指定されたディレクトリ構成が存在するかどうかをチェックします。不足しているディレクトリやファイルがあれば、警告メッセージを表示します。

まとめ

pathlibモジュールは、Pythonでのファイルシステム操作を強力かつ直感的に行うためのツールです。
今回紹介したスクリプトを参考にして、実際のプロジェクトでpathlibを活用し、ファイル操作を効率化してください!

0
0
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
0
0