Python•ファイル操作
Pythonのファイル操作:読み込み、書き込み、with open()
Python は with open(filename, mode) as f によってファイル記述子をきれいに管理し、エラー発生時でも自動クローズを保証します。
構文
with open(filename, mode, encoding="utf-8") as file:
content = file.read()
パラメータと値
この構文の主な構成要素と指定可能な値:
| パラメータ | 型 | 説明 |
|---|---|---|
| filename | str / Path | ディスク上の対象ファイルへのパス。 |
| mode | str | "r"(読込)、"w"(書込/上書)、"a"(追記)、"rb"(バイナリ)。 |
そのまま実行できるコード例
Compilra で実行可能Python をローカルにインストールせずに、この動作する完全なコード例を直接実行できます:
# In-memory File Simulation & io.StringIO
import io
# Simulating file read/write using Python in-memory buffers
virtual_file = io.StringIO()
# Writing content with context manager semantics
virtual_file.write("LOG: 2026-10-18 10:00:00 Server Initialized\n")
virtual_file.write("LOG: 2026-10-18 10:05:00 Database Connected\n")
virtual_file.write("LOG: 2026-10-18 10:10:00 Health Check PASSED\n")
# Reset buffer pointer to beginning
virtual_file.seek(0)
# Reading lines sequentially
print("--- Reading Virtual Log File ---")
for line_number, line in enumerate(virtual_file, start=1):
print(f"Line {line_number}: {line.strip()}")期待される出力:
--- Reading Virtual Log File --- Line 1: LOG: 2026-10-18 10:00:00 Server Initialized Line 2: LOG: 2026-10-18 10:05:00 Database Connected Line 3: LOG: 2026-10-18 10:10:00 Health Check PASSED
動作のしくみ: ステップ解説
- 7〜10行目: 複数行をストリームバッファに書き込みます。
- 13行目: seek(0) で読み込みポインタをファイルの先頭へ巻き戻します。
- 16〜18行目: ファイルストリームを1行ずつ効率的に反復処理します。
重要ポイント
- with 文はコンテキストマネージャを生成し、ブロック終了時に自動で file.close() を呼び出します。
- "w" モードは既存の内容を上書きし、"a" モードは末尾に新しい行を追記します。
- ファイルオブジェクトを直接反復すると1行ずつ遅延読み込みされ、大容量ファイルでもメモリを節約できます。
よくある間違い: with 文を使わずにファイルを開くこと
with を省略すると close() 前に例外が起きた場合ファイルハンドルが開いたまま残ります。
❌ 誤り
f = open("log.txt", "w")
f.write("data") # If error happens here, f is never closed!
f.close()✅ 正しい例
with open("log.txt", "w") as f:
f.write("data") # Automatically closed safely関連するPythonチュートリアルとコンパイラ
Pythonの Async/Await と asyncio 並行処理の基礎
Python の async def、await、asyncio ライブラリを使って非同期・並行コードを書く方法を学びましょう。
Pythonの例外処理:try、except、else、finally
Pythonの例外は try...except ブロックを使ってプログラムを停止させずに実行時エラーを安全に捕捉できます。
Python の文字列:スライス・エスケープ・組み込みメソッド
Python の文字列は豊富な変換用組み込みメソッドを備えた、イミュータブルな Unicode 文字シーケンスです。
Python オンラインコンパイラ
Compilra IDE で開く
Compilra で Python を実行・テストする
Compilraのクラウドコンパイラ上で事前設定した標準入力 (stdin) を使ってこのコードを実行できます。