Pythonでprint関数を用いてファイル書き込みを行うためのサンプルコード一覧
基本
output = 'sample.txt'
test_str = 'test'
f = open(output, 'w')
print(test_str, file=f)
f.close()with文
output = 'sample.txt'
test_str = 'test'
with open(output, "w") as f:
print(test_str, file=f)フォルダ作成+ファイル書き込み
import os
dir_path = 'sample'
output = 'sample.txt'
test_str = 'test'
if not os.path.exists(dir_path):
os.mkdir(dir_path)
with open(os.path.join(dir_path, output), "w") as f:
print(test_str, file=f)
