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

2024-09-29 17:23:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将不同变量的值保存在CSV文件中。但它每次都会打印另一个标题。我不想这样,我附上我的CSV文件快照供您理解Output 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()])

Tags: 文件csvorgimageclean标题outputopen
1条回答
网友
1楼 · 发布于 2024-09-29 17:23:16

尽量不要使用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&;什么时候应该完成writeheader'

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

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”是写的。因此,在数据停止/上次占用的位置追加新的数据行

相关问题 更多 >

    热门问题