ファイル読み書き関連リファレンス

ファイル読み書き

読み込みオープン


with open(path) as f:
f.read()

書き込みオープン


with open('./param.json', 'w') as f:
f.write(...)

1行ずつリストとして読み込み(行の最後に改行コードが付く)


with open(path, encoding='UTF-8') as f:
line = f.readlines()

リストをファイルに書き込む(改行コードは書き込み前に付与する必要あり)


with open(path, mode='w', encoding='UTF-8') as f:
f.writelines(line)

標準出力を特定のファイルに向けて書き込む

mystdout = open('result.html', 'w')
sys.stdout = mystdout

以降、print()は’result.html’に書き込まれる。
withを使っていないので、自分でclose()することを忘れずに。

タイトルとURLをコピーしました