チュートリアル

Python実践編:ファイル操作

Pythonファイル操作実践
広告エリア

はじめに

Python実践編では、実際の開発で必要になるスキルを学びます。第1回はファイル操作です。

テキストファイルの読み書き

ファイルを読む

# 基本的な読み込み
with open("sample.txt", "r", encoding="utf-8") as f:
    content = f.read()
    print(content)

# 1行ずつ読み込み
with open("sample.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line.strip())

# 全行をリストとして取得
with open("sample.txt", "r", encoding="utf-8") as f:
    lines = f.readlines()
    print(lines)

ファイルに書き込む

# 新規作成・上書き
with open("output.txt", "w", encoding="utf-8") as f:
    f.write("こんにちは\n")
    f.write("Python\n")

# 追記
with open("output.txt", "a", encoding="utf-8") as f:
    f.write("追加の行\n")

# 複数行を一度に書き込み
lines = ["1行目", "2行目", "3行目"]
with open("output.txt", "w", encoding="utf-8") as f:
    f.writelines(line + "\n" for line in lines)

with文の重要性

with文を使うと、ファイルが自動的に閉じられます。

# 良い例(with文を使用)
with open("file.txt", "r") as f:
    content = f.read()
# ここでファイルは自動的に閉じられる

# 悪い例(close忘れの可能性)
f = open("file.txt", "r")
content = f.read()
f.close()  # 忘れるとリソースリークの原因に

ファイルモード一覧

モード説明
r読み込み(デフォルト)
w書き込み(上書き)
a追記
x新規作成(既存ファイルがあるとエラー)
bバイナリモード
tテキストモード(デフォルト)
# バイナリファイルの読み込み
with open("image.png", "rb") as f:
    data = f.read()

# バイナリファイルの書き込み
with open("copy.png", "wb") as f:
    f.write(data)

CSVファイルの操作

import csv

# CSVを読み込む
with open("data.csv", "r", encoding="utf-8") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)  # ['列1', '列2', '列3']

# ヘッダー付きCSVを辞書として読み込む
with open("data.csv", "r", encoding="utf-8") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row["name"], row["age"])

# CSVに書き込む
data = [
    ["名前", "年齢", "職業"],
    ["太郎", 25, "エンジニア"],
    ["花子", 22, "デザイナー"],
]

with open("output.csv", "w", encoding="utf-8", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(data)

# 辞書からCSVに書き込む
users = [
    {"name": "太郎", "age": 25},
    {"name": "花子", "age": 22},
]

with open("output.csv", "w", encoding="utf-8", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=["name", "age"])
    writer.writeheader()
    writer.writerows(users)

JSONファイルの操作

import json

# JSONを読み込む
with open("data.json", "r", encoding="utf-8") as f:
    data = json.load(f)
    print(data)

# JSONに書き込む
data = {
    "name": "太郎",
    "age": 25,
    "skills": ["Python", "JavaScript"]
}

with open("output.json", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

# 文字列との変換
json_string = json.dumps(data, ensure_ascii=False)
parsed_data = json.loads(json_string)

pathlibでパス操作

Python 3.4以降はpathlibがおすすめです。

from pathlib import Path

# パスの作成
path = Path("documents") / "report.txt"
print(path)  # documents/report.txt

# ファイル操作
path = Path("sample.txt")
content = path.read_text(encoding="utf-8")
path.write_text("新しい内容", encoding="utf-8")

# パス情報の取得
print(path.name)       # sample.txt
print(path.stem)       # sample
print(path.suffix)     # .txt
print(path.parent)     # .
print(path.absolute()) # /home/user/sample.txt

# ファイル・ディレクトリの存在確認
print(path.exists())
print(path.is_file())
print(path.is_dir())

# ディレクトリ内のファイル一覧
for p in Path(".").iterdir():
    print(p)

# 再帰的にファイルを検索
for p in Path(".").glob("**/*.py"):
    print(p)

ディレクトリ操作

from pathlib import Path
import shutil

# ディレクトリ作成
Path("new_folder").mkdir(exist_ok=True)
Path("a/b/c").mkdir(parents=True, exist_ok=True)

# ファイル・ディレクトリの削除
Path("file.txt").unlink()  # ファイル削除
Path("empty_folder").rmdir()  # 空のディレクトリ削除
shutil.rmtree("folder")  # 中身ごと削除

# コピーと移動
shutil.copy("src.txt", "dst.txt")
shutil.copytree("src_dir", "dst_dir")
shutil.move("old.txt", "new.txt")

実践例:ログファイル処理

from pathlib import Path
from datetime import datetime

def parse_log_file(log_path):
    """ログファイルを解析してエラーを抽出"""
    errors = []

    with open(log_path, "r", encoding="utf-8") as f:
        for line_num, line in enumerate(f, 1):
            if "ERROR" in line:
                errors.append({
                    "line": line_num,
                    "content": line.strip()
                })

    return errors

def save_error_report(errors, output_path):
    """エラーレポートを保存"""
    with open(output_path, "w", encoding="utf-8") as f:
        f.write(f"エラーレポート - {datetime.now()}\n")
        f.write("=" * 50 + "\n\n")

        for error in errors:
            f.write(f"行 {error['line']}: {error['content']}\n")

        f.write(f"\n合計: {len(errors)}件のエラー\n")

# 使用例
errors = parse_log_file("app.log")
save_error_report(errors, "error_report.txt")

まとめ

  • with open() でファイルを安全に操作
  • csvモジュールでCSVファイルを扱う
  • jsonモジュールでJSONファイルを扱う
  • pathlibでモダンなパス操作
  • shutilでファイル・ディレクトリのコピー・移動

次回は例外処理について学びます。

広告エリア