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