在我的小python脚本中,我打开一个csv文件,给它写一个标题,处理一个循环,我在其中打开许多其他csv文件来查看它们,最后我每次循环写入第一个csv:
import csv
with open(output_file, 'wb') as f:
outfileWriter = csv.writer(f, delimiter=',')
# write header
for loop_file in a_list_of_files:
with open(loop_file) as s:
# calculate something on the file and write one line to f
现在最好保持f打开(即缩进循环),或者在对等循环后打开它?什么更pythonic /更快?
答案 0 :(得分:2)
打开和关闭文件需要付费:
所以,通常最好在开始处理循环之前打开文件一次,而不是每个循环重新打开它。
(更新)下面是一个示例,可以在您处理时写入输出文件,但如果处理中存在其他错误,则将其删除(因此您不会看到完全结果的部分结果)。
import csv
with open(output_file, 'wb') as f:
outfileWriter = csv.writer(f, delimiter=',')
# write header
try:
for loop_file in a_list_of_files:
with open(loop_file) as s:
# calculate something on the file and write one line to f
outfileWriter.write(something)
except:
# close and delete the file. the ctx manager will try to close
# the file again, but that's harmless.
f.close()
os.remove(output_file)
raise