Python pathlibでファイルの作成・読み書き・削除を行う完全ガイド

 

ファイルの作成

touch() – 空ファイルの作成

from pathlib import Path

# 新しいファイルを作成
file_path = Path('new_file.txt')
file_path.touch()

# 既存ファイルのタイムスタンプを更新
file_path.touch(exist_ok=True)

親ディレクトリも同時に作成

from pathlib import Path

file_path = Path('data/subfolder/new_file.txt')
# 親ディレクトリが存在しない場合は作成
file_path.parent.mkdir(parents=True, exist_ok=True)
file_path.touch()

ファイルのオープン

open() – ファイルを開く

from pathlib import Path

file_path = Path('sample.txt')

# テキストファイルを開く
with file_path.open('r', encoding='utf-8') as f:
    content = f.read()

# バイナリファイルを開く
with file_path.open('rb') as f:
    binary_data = f.read()

ファイルの読み取り

read_text() – テキストファイル全体を読む

from pathlib import Path

file_path = Path('sample.txt')

# ファイル全体を文字列として読み取り
content = file_path.read_text(encoding='utf-8')
print(content)

read_bytes() – バイナリファイル全体を読む

from pathlib import Path

file_path = Path('image.jpg')

# ファイル全体をバイト列として読み取り
binary_data = file_path.read_bytes()
print(len(binary_data))  # ファイルサイズ

行単位での読み取り

from pathlib import Path

file_path = Path('sample.txt')

# 行単位で読み取り
with file_path.open('r', encoding='utf-8') as f:
    for line_num, line in enumerate(f, 1):
        print(f'{line_num}: {line.strip()}')

ファイルの書き込み

write_text() – テキストを書き込む

from pathlib import Path

file_path = Path('output.txt')

# テキストをファイルに書き込み
content = 'Hello, World!\nThis is a test file.'
file_path.write_text(content, encoding='utf-8')

write_bytes() – バイナリデータを書き込む

from pathlib import Path

file_path = Path('binary_data.bin')

# バイナリデータを書き込み
binary_data = b'\x00\x01\x02\x03\x04\x05'
file_path.write_bytes(binary_data)

追記モードでの書き込み

from pathlib import Path

file_path = Path('log.txt')

# ファイルに追記
with file_path.open('a', encoding='utf-8') as f:
    f.write('\nNew log entry')

ファイルの削除

unlink() – ファイルを削除

from pathlib import Path

file_path = Path('temp_file.txt')

# ファイルが存在する場合のみ削除
if file_path.exists():
    file_path.unlink()

# Python 3.8以降では、missing_ok=Trueで存在チェック不要
file_path.unlink(missing_ok=True)

実用的な使用例

ログファイルの管理

from pathlib import Path
from datetime import datetime

def write_log(message, log_file='app.log'):
    """ログメッセージをファイルに記録"""
    log_path = Path(log_file)
    timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    log_entry = f'[{timestamp}] {message}\n'
    
    with log_path.open('a', encoding='utf-8') as f:
        f.write(log_entry)

# 使用例
write_log('アプリケーション開始')
write_log('処理完了')

CSVファイルの処理

from pathlib import Path
import csv

def read_csv_data(csv_file):
    """CSVファイルを読み取り"""
    csv_path = Path(csv_file)
    
    if not csv_path.exists():
        return []
    
    with csv_path.open('r', encoding='utf-8') as f:
        reader = csv.DictReader(f)
        return list(reader)

def write_csv_data(csv_file, data, headers):
    """CSVファイルに書き込み"""
    csv_path = Path(csv_file)
    
    with csv_path.open('w', newline='', encoding='utf-8') as f:
        writer = csv.DictWriter(f, fieldnames=headers)
        writer.writeheader()
        writer.writerows(data)

# 使用例
data = [
    {'名前': '田中', '年齢': 30},
    {'名前': '佐藤', '年齢': 25}
]
write_csv_data('users.csv', data, ['名前', '年齢'])

ファイルのバックアップ

from pathlib import Path
import shutil

def backup_file(source_file, backup_dir='backup'):
    """ファイルをバックアップ"""
    source_path = Path(source_file)
    backup_path = Path(backup_dir)
    
    if not source_path.exists():
        print('元ファイルが存在しません')
        return False
    
    # バックアップディレクトリを作成
    backup_path.mkdir(exist_ok=True)
    
    # バックアップファイル名を生成
    backup_file = backup_path / source_path.name
    
    # ファイルをコピー
    shutil.copy2(source_path, backup_file)
    print(f'バックアップ完了: {backup_file}')
    return True

# 使用例
backup_file('important_data.xlsx')

エラーハンドリング

安全なファイル操作

from pathlib import Path

def safe_read_file(file_path):
    """安全なファイル読み取り"""
    path = Path(file_path)
    
    try:
        if not path.exists():
            print(f'ファイルが存在しません: {path}')
            return None
        
        content = path.read_text(encoding='utf-8')
        return content
    
    except PermissionError:
        print(f'ファイルへのアクセス権限がありません: {path}')
    except UnicodeDecodeError:
        print(f'ファイルの文字エンコーディングエラー: {path}')
    except Exception as e:
        print(f'予期しないエラー: {e}')
    
    return None

# 使用例
content = safe_read_file('data.txt')
if content:
    print(content)

ファイル情報の取得

ファイルの統計情報

from pathlib import Path
import os

def get_file_info(file_path):
    """ファイルの詳細情報を取得"""
    path = Path(file_path)
    
    if not path.exists():
        return None
    
    stat = path.stat()
    
    return {
        'サイズ': stat.st_size,
        '作成日時': stat.st_ctime,
        '更新日時': stat.st_mtime,
        'アクセス日時': stat.st_atime,
        '権限': oct(stat.st_mode)[-3:]
    }

# 使用例
info = get_file_info('sample.txt')
if info:
    for key, value in info.items():
        print(f'{key}: {value}')

まとめ

pathlibを使ったファイル操作は、従来のopenやosモジュールよりも直感的で読みやすいコードが書けます。特にread_text()write_text()touch()unlink()などのメソッドを活用することで、簡潔なファイル操作が可能になります。

■プロンプトだけでオリジナルアプリを開発・公開してみた!!

■AI時代の第一歩!「AI駆動開発コース」はじめました!

テックジム東京本校で先行開始。

■テックジム東京本校

「武田塾」のプログラミング版といえば「テックジム」。
講義動画なし、教科書なし。「進捗管理とコーチング」で効率学習。
より早く、より安く、しかも対面型のプログラミングスクールです。

<短期講習>5日で5万円の「Pythonミニキャンプ」開催中。

<月1開催>放送作家による映像ディレクター養成講座

<オンライン無料>ゼロから始めるPython爆速講座