4-1

ファイル入出力の基本

ファイルとは

プログラムを終了してもデータを保持するためには、ファイルに保存する必要があります。Pythonでは、テキストファイルやバイナリファイルを読み書きすることができます。

ファイルのオープン

ファイルの入出力では、オープン → 読み書き → クローズ の流れが基本です。

ファイル操作の基本フロー📂open()✏️read / writeclose()with open("file.txt") as f: ← 自動でclose

open() 関数でファイルを開きます。

python
# ファイルを開くf = open("sample.txt", "r")   # 読み込みモードで開く# ファイルを読むcontent = f.read()print(content)

モードの種類

| モード | 説明 | |:---:|:---| | "r" | 読み込み(デフォルト)。ファイルが存在しない場合エラー | | "w" | 書き込み。ファイルが存在する場合は上書き | | "a" | 追記。ファイルの末尾に追記 | | "x" | 新規作成。ファイルが既に存在する場合はエラー | | "b" | バイナリモード("rb", "wb" など組み合わせて使う) |

ファイルのクローズ

ファイルを使い終わったら必ず close() で閉じる必要があります。

python
f = open("sample.txt", "r")content = f.read()f.close()   # 必ず閉じる!

with文を使う(推奨)

with 文を使うと、ブロックを抜けたときに自動でファイルが閉じられます。これが推奨の方法です。

python
with open("sample.txt", "r") as f:    content = f.read()    print(content)# with ブロックを抜けると自動で閉じられる

ファイルの読み込み

read() - 全体を読む

python
with open("sample.txt", "r", encoding="utf-8") as f:    content = f.read()   # ファイル全体を文字列として読む    print(content)

readline() - 1行ずつ読む

python
with open("sample.txt", "r", encoding="utf-8") as f:    line = f.readline()   # 1行読む    while line:        print(line, end="")   # end="" で改行の重複を防ぐ        line = f.readline()

readlines() - 全行をリストで読む

python
with open("sample.txt", "r", encoding="utf-8") as f:    lines = f.readlines()   # ["行1", "行2", ...]    for line in lines:        print(line.rstrip())   # 末尾の改行を除去

forループで1行ずつ読む(最も効率的)

python
with open("sample.txt", "r", encoding="utf-8") as f:    for line in f:   # ファイルオブジェクトはイテラブル        print(line.rstrip())

ファイルへの書き込み

write() - 文字列を書く

python
# ファイルを新規作成して書き込むwith open("output.txt", "w", encoding="utf-8") as f:    f.write("Hello, Python!")    f.write("ファイルに書き込みました。")

複数行の書き込み

python
lines = ["1行目", "2行目", "3行目"]with open("output.txt", "w", encoding="utf-8") as f:    f.writelines(lines)   # リストの各要素を書き込む
python
with open("output.txt", "w", encoding="utf-8") as f:    print("Hello, World!", file=f)   # fileパラメータを指定    print(42, "Python", file=f)

エンコーディング

日本語を含むファイルを扱う場合は、エンコーディングを明示することが重要です。

python
# UTF-8 で読み書き(推奨)with open("japanese.txt", "r", encoding="utf-8") as f:    content = f.read()# Shift-JIS(古いWindowsファイル)with open("old_file.txt", "r", encoding="shift-jis") as f:    content = f.read()

練習: 行数のカウント

基礎

テキストファイルの行数を返す関数 count_lines(filename) を定義してください。

練習: 単語数のカウント

基礎

テキストファイルの単語数を返す関数 count_words(filename) を定義してください。