記事一覧へ戻る 本の順番で続きを読む

ファイル操作 - 読み書きの基本

Python3初級 | 2026/02/18 15:36

ファイル操作

ファイルを開く・閉じる

# with文を使う(推奨 - 自動でclose)
with open("sample.txt", "r", encoding="utf-8") as f:
    content = f.read()
    print(content)

ファイルのモード

モード 説明
"r" 読み取り(デフォルト)
"w" 書き込み(既存内容を上書き)
"a" 追記(末尾に追加)
"x" 新規作成(既存なら失敗)
"b" バイナリモード
"r+" 読み書き

テキストファイルの読み込み

# 全体を一度に読む
with open("data.txt", "r", encoding="utf-8") as f:
    content = f.read()

# 1行ずつ読む(メモリ効率が良い)
with open("data.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line.strip())  # 改行を除去

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

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

# 新規作成 or 上書き
with open("output.txt", "w", encoding="utf-8") as f:
    f.write("1行目\n")
    f.write("2行目\n")

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

CSVファイルの操作

import csv

# CSVの読み込み
with open("users.csv", "r", encoding="utf-8") as f:
    reader = csv.reader(f)
    header = next(reader)  # ヘッダー行を取得
    for row in reader:
        print(row)

# 辞書形式で読み込み
with open("users.csv", "r", encoding="utf-8") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row["name"], row["age"])

# CSVの書き込み
data = [
    ["name", "age", "city"],
    ["太郎", 25, "東京"],
    ["花子", 22, "大阪"],
]
with open("output.csv", "w", encoding="utf-8", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(data)

JSONファイルの操作

import json

# JSONの読み込み
with open("config.json", "r", encoding="utf-8") as f:
    data = json.load(f)
    print(data["name"])

# JSONの書き込み
config = {
    "name": "MyApp",
    "version": "1.0",
    "settings": {
        "debug": True,
        "port": 8080
    }
}
with open("config.json", "w", encoding="utf-8") as f:
    json.dump(config, f, ensure_ascii=False, indent=2)

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

pathlib(モダンなパス操作)

from pathlib import Path

# パスの作成
p = Path("data") / "output" / "result.txt"
print(p)  # data/output/result.txt

# ファイルの存在チェック
if p.exists():
    print("ファイルが存在します")

# ディレクトリ作成
Path("data/output").mkdir(parents=True, exist_ok=True)

# ファイルの読み書き
p = Path("hello.txt")
p.write_text("こんにちは", encoding="utf-8")
content = p.read_text(encoding="utf-8")

# ファイル一覧
for f in Path(".").glob("*.py"):
    print(f.name)

まとめ

  • with open() を使ってファイルを安全に操作する
  • encoding="utf-8" を常に指定する(日本語対応)
  • CSVは csv モジュール、JSONは json モジュールを使う
  • pathlib.Path でモダンなパス操作ができる