简体   繁体   English

如何在下一个写入 csv 文件的循环中跳过 header - Python

[英]How skip a header in the next loop of writing data in csv file - Python

I writting a script, where I dowload a data from json file (about temperature and data from datetime) and I want save the data i csv file.我写了一个脚本,我从 json 文件下载了一个数据(关于温度和日期时间的数据),我想将数据保存在 csv 文件中。 The script has a schedule set every minute to download new data from json. I have a problem with one thing.该脚本每分钟设置一个时间表,从 json 下载新数据。我有一个问题。 Running the code causes the data to write correctly, but each time with a header. The question is how to save the header only once?运行代码导致数据写入正确,但每次都是header。问题是如何只保存一次header?

My script: ...我的脚本:...

with open('Temp.csv', 'a', newline='') as file:
    fieldnames = ['Date', 'Temp']
    writer = csv.DictWriter(file, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerow({'Date':now, 'Temp':Temperatura})

My DataFrame look like this:我的 DataFrame 看起来像这样:

enter image description here在此处输入图像描述

but I want: enter image description here但我想:在这里输入图片描述

Thanks for help, Dawid谢谢你的帮助,大卫

You need to write the header before the first row.您需要在第一行之前写上 header。 So check the existence of the file to decide on writing the header.所以检查文件是否存在,决定写入header。


import os 

file_exists = os.path.exists('Temp.csv')

with open('Temp.csv', 'a', newline='') as file:
    fieldnames = ['Date', 'Temp']
    writer = csv.DictWriter(file, fieldnames=fieldnames)
    if not file_exists:
        writer.writeheader() # So the header is written only once just before the first row
    writer.writerow({'Date':now, 'Temp':Temperatura})

For the rest rows, since the csv file exists, header is not written again.对于rest行,由于csv文件存在,所以header不再写入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM