python csv,仅一次写入标头 [英] python csv, writing headers only once

查看:718
本文介绍了python csv,仅一次写入标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个程序可以从.Json创建CSV.

So I have a program that creates CSV from .Json.

首先,我加载json文件.

First I load the json file.

f = open('Data.json')
data = json.load(f)
f.close()

然后我遍历它,寻找一个特定的关键字(如果找到该关键字).我将与此相关的所有内容都写到.csv文件中.

Then I go through it, looking for a specific keyword, if I find that keyword. I'll write everything related to that in a .csv file.

for item in data:
    if "light" in item:
       write_light_csv('light.csv', item)

这是我的write_light_csv函数:

def write_light_csv(filename,dic):

    with open (filename,'a') as csvfile:
        headers = ['TimeStamp', 'light','Proximity']
        writer = csv.DictWriter(csvfile, delimiter=',', lineterminator='\n',fieldnames=headers)

        writer.writeheader()

        writer.writerow({'TimeStamp': dic['ts'], 'light' : dic['light'],'Proximity' : dic['prox']})

起初我以wb+作为模式,但是每次打开文件进行写入时,这都会清除所有内容.我用a替换了它,现在每次写入时,都会添加一个标题.如何确保标头只写一次?.

I initially had wb+ as the mode, but that cleared everything each time the file was opened for writing. I replaced that with a and now every time it writes, it adds a header. How do I make sure that header is only written once?.

推荐答案

您可以检查文件是否已存在,然后不调用writeheader(),因为要使用附加选项打开文件.

You could check if file is already exists and then don't call writeheader() since you're opening the file with an append option.

类似的东西:

import os.path


file_exists = os.path.isfile(filename)

with open (filename, 'a') as csvfile:
    headers = ['TimeStamp', 'light', 'Proximity']
    writer = csv.DictWriter(csvfile, delimiter=',', lineterminator='\n',fieldnames=headers)

    if not file_exists:
        writer.writeheader()  # file doesn't exist yet, write a header

    writer.writerow({'TimeStamp': dic['ts'], 'light': dic['light'], 'Proximity': dic['prox']})

这篇关于python csv,仅一次写入标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆