【Python基礎】ファイルへの書き込みと追記|write()とappendモード

ファイルへの書き込みと追記

モード "w" で上書き書き込み、"a" で末尾に追記します。

1. ファイルへの書き込み(上書き)

with open("output.txt", "w", encoding="utf-8") as f:
    f.write("1行目のテキスト
")
    f.write("2行目のテキスト
")

# 確認
with open("output.txt", "r", encoding="utf-8") as f:
    print(f.read())
▶ 出力結果

1行目のテキスト
2行目のテキスト

2. 追記モード(”a”)

with open("log.txt", "a", encoding="utf-8") as f:
    f.write("新しいログを追加
")

# "w" は既存内容を消去するが、"a" は消さずに末尾に追加する
▶ 出力結果(log.txtへの追記)

新しいログを追加

3. リストをファイルに書き出す

scores = ["田中: 85点", "鈴木: 92点", "佐藤: 78点"]

with open("scores.txt", "w", encoding="utf-8") as f:
    for score in scores:
        f.write(score + "
")

# 確認
with open("scores.txt", "r", encoding="utf-8") as f:
    print(f.read())
▶ 出力結果

田中: 85点
鈴木: 92点
佐藤: 78点
< 前の記事ファイルを開いて読み込む
次の記事 >with構文を使った安全なファイル操作

コメントする

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

上部へスクロール