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

ファイル読み書き入門:with open の使い方【Day 22】

Last updated at Posted at 2025-12-21

Qiita Advent Calendar 2025 のパイソニスタの一人アドカレ Day22 の記事です。

ファイル読み書き入門:with open の使い方

Python でのファイル操作は、テキストデータの読み書きに便利です。
with open を使うと、ファイルを安全に開閉できます。

1. ファイルを開く基本

with open("sample.txt", "r") as f:
    content = f.read()
    print(content)
  • "sample.txt":読み込むファイル名
  • "r":読み込みモード(read)
  • as f:ファイルオブジェクトの名前
  • with を使うと 自動でファイルを閉じる

2. 書き込み(write)

with open("output.txt", "w") as f:
    f.write("Hello, Python!\n")
  • "w":書き込みモード(上書き)
  • 既存の内容は上書きされる

■ 追記する場合

with open("output.txt", "a") as f:
    f.write("追加の行\n")
  • "a":追記モード(append)

3. 行ごとに読み込む

with open("sample.txt", "r") as f:
    for line in f:
        print(line.strip())  # 改行を削除して表示
  • ファイルを 1行ずつ処理 できる
  • strip() で末尾の改行を削除

4. エラーに備える

try:
    with open("not_exist.txt", "r") as f:
        print(f.read())
except FileNotFoundError:
    print("ファイルが存在しません")
  • ファイルがない場合の安全対策

5. 今日のまとめ

  • with open("ファイル名", モード) as f: で安全に開閉
  • "r":読み込み、"w":書き込み(上書き)、"a":追記
  • for line in f: で行単位の読み込み
  • エラー対策として try-except と組み合わせると安全

6. ミニ問題

Q1.
data.txt を読み込んで、各行の文字数を表示するコードを書いてください。

Q2.
log.txt"ログ記録\n" を追記するコードを書いてください。

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