1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python】Python のファイル操作

Posted at

はじめに

Python でファイルを扱うときに必ず登場するキーワードが
open / read / write / with の4つ。

本記事では、初学者が迷うポイントをほどよくスッキリさせつつ、Pythonic(Pythonらしい)書き方も含めて整理します。


1. open():ファイルの扉を開く

Python でファイル操作を始めるには、まず open() を使ってファイルを開きます。
これは「ファイルへの入口(ハンドル)を取得する」操作に相当します。

基本の書き方

f = open("data.txt", "r")

主なファイルモード

モード 意味 特徴
"r" 読み込み デフォルト。存在しないとエラー
"w" 書き込み 既存内容を全削除して新しく書く
"a" 追記 ファイルの末尾に追加
"rb" バイナリ読み込み 画像・音声など
"wb" バイナリ書き込み 同上

2. read():ファイル内容を読み込む

ファイル内容を取得するには read() 系のメソッドを使います。

全文読み込み

with open("data.txt", "r", encoding="utf-8") as f:
    text = f.read()

1行ずつ読み込み

with open("data.txt", "r", encoding="utf-8") as f:
    line = f.readline()

複数行をまとめて読み込み(リスト)

with open("data.txt", "r", encoding="utf-8") as f:
    lines = f.readlines()

最も Pythonic な書き方(for ループ)

with open("data.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line.strip())

ファイルオブジェクトはイテラブルなので、行単位処理は for 文が最も自然で効率的です。


3. write():内容を書き込む

ファイルへ内容を書き込みたいときは write() を使います。

上書き

with open("memo.txt", "w", encoding="utf-8") as f:
    f.write("Hello Python!")

追記

with open("memo.txt", "a", encoding="utf-8") as f:
    f.write("\n追加のメッセージ")

注意点

  • "w"既存内容をすべて消す
  • "a" は末尾に追加するだけ
    誤って "w" を使ってデータを吹き飛ばす事故はよく起きるので注意!

4. with:自動で close() してくれる最高の相棒

with open(...) を使うことで、処理終了後に自動で close() を実行してくれます。
これは Python の コンテキストマネージャ という仕組み。

なぜ with を使うべき?

  • ファイルを閉じ忘れるリスクがゼロ
  • 例外が起きても安全に後処理される
  • コードが読みやすい

実際のコード

with open("data.txt", "r", encoding="utf-8") as f:
    content = f.read()
    print(content)

「開けたら閉める」を自動化する、まるで優秀な執事。


5. ファイルコピーのサンプルコード

実践的な例として、ファイルの内容を行ごとコピーするコードを紹介します。

with open("src.txt", "r", encoding="utf-8") as src:
    with open("dest.txt", "w", encoding="utf-8") as dest:
        for line in src:
            dest.write(line)

Pythonic かつシンプル。
行処理・読み書き・with の3つが一度に理解できます。


6. よくあるトラブルと注意点

encoding を忘れて文字化け

特に Windows で注意。

open("file.txt", "r", encoding="utf-8")

"w" を使って既存ファイルを消してしまう

「え?昨日のデータ全部ないんだけど?」事件がよく起こる。
追記は必ず "a"

close() 書き忘れ

with を使えば全部解決。


まとめ

技術 役割
open() ファイルを開く
read() 読む
write() 書く
with 自動で閉じる(安全)

Python のファイル操作はこの4つさえ理解していれば実務レベルで十分戦えます。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?