如何避免在循环中写入CSV时重复标题



我想将不同变量的值保存在CSV文件中。但它每次都会打印另一个页眉。我不想这样,我附上我的CSV文件快照以供您理解。输出csv

file_orimg = open('Org_image.csv', 'a', newline='')
writer_orimg = csv.writer(file_orimg, delimiter='t',lineterminator='n',)
writer_orimg.writerow(["Image Name", "epsilon","MSE", "SSIM", "Prediction", "Probability"])
for i in images:
writer_orimg.writerow([i, epsilon, mse, ssim, clean_pred, clean_prob, label_idx.item()])

尽量不要使用writerow来编写标题。您可以在CSV python模块中查看DictWriter,这样可以更高效地编写标题和行!

list_of_headers = ['No.', 'Image Name', 'Epsilon']
dictionary_content = {'No.': 1, 'Image Name': 'image_123', 'Epsilon': 'what?'}
w = csv.DictWriter(my_csvfile, fieldnames= list_of_headers)
w.writeheader()
w.writerow(dictionay_content)

希望这能有所帮助,如果有任何需要纠正的地方,请告诉我!

编辑:回答'where&什么时候应该写头

我使用os-python模块来确定文件是否存在,如果不存在,我将创建一个!

if os.path.isfile(filename):
with open(filename, 'a', newline='') as my_file:
w = csv.DictWriter(my_file, fieldnames= list_of_headers)
w.writerow(dictionay_content)
else:
with open(filename, 'w', newline='') as my_file:
w = csv.DictWriter(my_file, fieldnames= list_of_headers)
w.writeheader()
w.writerow(dictionay_content)

注意"a"表示追加,而"w"表示写入。因此,从数据停止/上次占用的位置添加新的数据行。

最新更新