【问题标题】:How to avoid repeating header when Writing to CSV in loop?循环写入CSV时如何避免重复标题?
【发布时间】:2020-05-11 01:05:14
【问题描述】:

我想将不同变量的值保存在 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()])

【问题讨论】:

    标签: python csv csv-write-stream


    【解决方案1】:

    尽量不要使用 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)
    

    希望对你有帮助,如果有什么需要改正的请告诉我!

    编辑:回答“应该在何时何地完成 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'表示写入。因此,从停止/上次占用的位置附加新的数据行。

    【讨论】:

    • 应该在循环还是在循环外?
    • 创建一个 if 条件来检查是否需要写入标题。如果标头存在,则无需编写标头。 Empty/new CSV = write headers,你可以从那时起省略写入标题。
    • 我已经继续并添加了一个部分来回答您的循环问题。
    • 我正在写这个,因为这些不是常量值,而是在每次迭代中都在变化的变量值,dictionary_content = ({'Image': i, 'epsilon': epsilon ,'MSE': mse, 'SSIM': ssim, 'Prediction': 预测)
    • 感谢您的宝贵时间。我通过stackoverflow.com/questions/24661525/… 得到了我的解决方案
    猜你喜欢
    • 2017-12-27
    • 1970-01-01
    • 1970-01-01
    • 2014-10-21
    • 1970-01-01
    • 1970-01-01
    • 2018-07-19
    • 2012-06-24
    • 1970-01-01
    相关资源
    最近更新 更多