ファイルを開いて読み込む
open() 関数でファイルを開き、read() や readlines() で内容を取得します。
1. ファイル全体を読み込む(read)
# sample.txt の内容:
# こんにちは
# Pythonのファイル操作
with open("sample.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)
▶ 出力結果
こんにちは Pythonのファイル操作
2. 1行ずつ読み込む(readlines)
with open("sample.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
for i, line in enumerate(lines, 1):
print(f"{i}行目:{line.strip()}")
▶ 出力結果
1行目:こんにちは 2行目:Pythonのファイル操作
3. open()のモード指定
# よく使うモード
# "r" → 読み込み(デフォルト)
# "w" → 書き込み(上書き)
# "a" → 追記
# "rb" → バイナリ読み込み(画像など)
# ファイルが存在しない場合の対処
import os
if os.path.exists("sample.txt"):
with open("sample.txt", "r", encoding="utf-8") as f:
print(f.read())
else:
print("ファイルが見つかりません")
▶ 出力結果
こんにちは Pythonのファイル操作
