Python入門|ファイルの読み書きを基礎から解説
プログラムで処理したデータをファイルに保存したり、ファイルからデータを読み込んだりする操作は、実用的なプログラムに欠かせません。この記事では、Pythonでのファイル読み書きの基本を、テキストファイルやCSVファイルの具体例を交えて解説します。
ファイル操作の基本
Pythonでファイルを扱うには open() 関数を使います。ファイルを開いて、読み書きし、最後に閉じるという流れが基本です。
open()関数の基本
open() 関数は、ファイルのパスとモード(読み取り・書き込みなど)を指定して使います。
# ファイルを読み取りモードで開く
f = open("sample.txt", "r", encoding="utf-8")
content = f.read()
print(content)
f.close() # 必ず閉じる
主なモードは以下の通りです。
"r": 読み取り(read)。ファイルが存在しないとエラー"w": 書き込み(write)。ファイルが存在すれば上書き、なければ新規作成"a": 追記(append)。ファイルの末尾に追加"x": 新規作成(exclusive)。ファイルが存在するとエラー
with文を使った安全なファイル操作
f.close() を書き忘れるとファイルが正しく閉じられない場合があります。with 文を使うと、ブロックを抜けたときに自動的にファイルが閉じられるため安全です。
# with文を使った読み取り(推奨)
with open("sample.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)
# ブロックを出ると自動的にファイルが閉じられる
以降の例ではすべて with 文を使います。
テキストファイルの読み込み
テキストファイルの読み込みにはいくつかの方法があります。データの使い方に応じて選びましょう。
ファイル全体を一度に読む
with open("message.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)
小さなファイルに向いていますが、巨大なファイルではメモリを大量に使うため注意が必要です。
1行ずつ読む
with open("names.txt", "r", encoding="utf-8") as f:
for line in f:
# strip()で末尾の改行を除去
print(line.strip())
for文でファイルオブジェクトをループすると、1行ずつ処理できます。大きなファイルでもメモリを圧迫しません。
全行をリストとして読む
with open("names.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
print(lines) # ['田中\n', '佐藤\n', '鈴木\n']
print(len(lines)) # 3
# 改行を取り除いたリストを作る
names = [line.strip() for line in lines]
print(names) # ['田中', '佐藤', '鈴木']
テキストファイルへの書き込み
処理結果をファイルに保存する方法を見ていきましょう。
新規作成または上書き
"w" モードで開くと、ファイルの内容がすべて消えて新しく書き込まれます。ファイルが存在しない場合は新規作成されます。
# 報告書を出力
report = [
"月次報告書",
"==========",
"売上: 1,500,000円",
"経費: 300,000円",
"利益: 1,200,000円",
]
with open("report.txt", "w", encoding="utf-8") as f:
for line in report:
f.write(line + "\n")
print("report.txt を作成しました。")
既存ファイルへの追記
"a" モードで開くと、ファイルの末尾にデータを追加できます。ログファイルの記録などに便利です。
import datetime
def write_log(message):
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open("app.log", "a", encoding="utf-8") as f:
f.write(f"[{now}] {message}\n")
write_log("アプリケーション起動")
write_log("データの読み込み完了")
write_log("処理が正常に終了")
app.log の中身:
[2026-04-01 10:00:00] アプリケーション起動
[2026-04-01 10:00:01] データの読み込み完了
[2026-04-01 10:00:02] 処理が正常に終了
CSVファイルの読み込み
CSV(Comma-Separated Values)は、データをカンマで区切って保存する形式で、表計算ソフトとの連携によく使われます。Pythonには標準ライブラリの csv モジュールが用意されています。
csv.readerで読み込む
以下のような sales.csv があるとします。
日付,商品名,数量,単価
2026-04-01,りんご,5,150
2026-04-01,バナナ,3,100
2026-04-02,みかん,10,80
2026-04-02,りんご,2,150
import csv
with open("sales.csv", "r", encoding="utf-8") as f:
reader = csv.reader(f)
header = next(reader) # ヘッダー行を取得
print(f"列名: {header}")
for row in reader:
date, product, quantity, price = row
total = int(quantity) * int(price)
print(f"{date} {product}: {quantity}個 x {price}円 = {total}円")
実行結果:
列名: ['日付', '商品名', '数量', '単価']
2026-04-01 りんご: 5個 x 150円 = 750円
2026-04-01 バナナ: 3個 x 100円 = 300円
2026-04-02 みかん: 10個 x 80円 = 800円
2026-04-02 りんご: 2個 x 150円 = 300円
csv.DictReaderで列名付きで読み込む
DictReader を使うと、各行を辞書として読み込めます。列名で値にアクセスできるため、コードの可読性が上がります。
import csv
with open("sales.csv", "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
total_sales = 0
for row in reader:
subtotal = int(row["数量"]) * int(row["単価"])
total_sales += subtotal
print(f"{row['商品名']}: {subtotal}円")
print(f"売上合計: {total_sales}円")
CSVファイルへの書き込み
処理結果をCSVファイルとして出力する方法も確認しましょう。
csv.writerで書き込む
import csv
# 集計データを作成
data = [
["商品名", "総数量", "売上合計"],
["りんご", 7, 1050],
["バナナ", 3, 300],
["みかん", 10, 800],
]
with open("summary.csv", "w", encoding="utf-8", newline="") as f:
writer = csv.writer(f)
for row in data:
writer.writerow(row)
print("summary.csv を作成しました。")
newline="" を指定するのは、Windows環境で余計な空行が入るのを防ぐためです。
csv.DictWriterで辞書から書き込む
import csv
members = [
{"名前": "田中太郎", "部署": "営業", "入社年": 2020},
{"名前": "佐藤花子", "部署": "開発", "入社年": 2021},
{"名前": "鈴木一郎", "部署": "総務", "入社年": 2019},
]
fieldnames = ["名前", "部署", "入社年"]
with open("members.csv", "w", encoding="utf-8", newline="") as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader() # ヘッダー行を書き込む
writer.writerows(members) # 全行を一度に書き込む
print("members.csv を作成しました。")
実践例: 成績データの集計
ここまでの知識を組み合わせて、成績CSVを読み込み、集計結果をテキストファイルに出力するプログラムを作ってみましょう。
成績データの読み込みと集計
まず、以下のような grades.csv を用意します。
名前,国語,数学,英語
田中,78,85,92
佐藤,90,72,88
鈴木,85,95,76
高橋,70,80,84
import csv
# CSVを読み込んで集計
students = []
with open("grades.csv", "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
name = row["名前"]
scores = {
"国語": int(row["国語"]),
"数学": int(row["数学"]),
"英語": int(row["英語"]),
}
avg = sum(scores.values()) / len(scores)
students.append({"name": name, "scores": scores, "average": avg})
# 平均点の高い順にソート
students.sort(key=lambda s: s["average"], reverse=True)
# 集計結果をテキストファイルに出力
with open("grade_report.txt", "w", encoding="utf-8") as f:
f.write("成績レポート\n")
f.write("=" * 30 + "\n\n")
for rank, student in enumerate(students, start=1):
f.write(f"{rank}位: {student['name']}(平均 {student['average']:.1f}点)\n")
for subject, score in student["scores"].items():
f.write(f" {subject}: {score}点\n")
f.write("\n")
# 科目別平均
f.write("科目別平均\n")
f.write("-" * 20 + "\n")
for subject in ["国語", "数学", "英語"]:
avg = sum(s["scores"][subject] for s in students) / len(students)
f.write(f" {subject}: {avg:.1f}点\n")
print("grade_report.txt を作成しました。")
エラー処理
ファイル操作ではエラーが起きやすいため、適切にエラーを処理することが大切です。
よくあるエラーと対策
# ファイルが存在しない場合
try:
with open("nonexistent.txt", "r", encoding="utf-8") as f:
content = f.read()
except FileNotFoundError:
print("ファイルが見つかりません。パスを確認してください。")
# パーミッションエラー(読み取り権限がない場合)
try:
with open("protected.txt", "r", encoding="utf-8") as f:
content = f.read()
except PermissionError:
print("ファイルの読み取り権限がありません。")
ファイルの存在確認
import os
filename = "data.csv"
if os.path.exists(filename):
print(f"{filename} は存在します。")
with open(filename, "r", encoding="utf-8") as f:
content = f.read()
else:
print(f"{filename} は存在しません。")
pathlibを使ったファイル操作
Python 3.4以降では、pathlib モジュールを使ったファイル操作も推奨されています。
from pathlib import Path
# ファイルの読み込み
p = Path("sample.txt")
if p.exists():
content = p.read_text(encoding="utf-8")
print(content)
# ファイルへの書き込み
output = Path("output.txt")
output.write_text("Hello, Python!\n", encoding="utf-8")
まとめ
この記事では、Pythonでのファイル読み書きの基本を解説しました。
open()関数でファイルを開き、"r"で読み取り、"w"で書き込み、"a"で追記するwith文を使うとファイルの閉じ忘れを防げるcsvモジュールでCSVファイルの読み書きができるDictReaderやDictWriterを使うと列名で操作できて便利try-exceptでファイル操作時のエラーに対応する
まずは簡単なテキストファイルの読み書きから試し、次にCSVの読み込みや集計に挑戦してみてください。ファイル操作ができるようになると、作れるプログラムの幅が大きく広がります。