python csv,只写一次标题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28325622/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:06:06  来源:igfitidea点击:

python csv, writing headers only once

pythoncsv

提问by cyberbemon

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

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

First I load the json file.

首先我加载json文件。

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

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.

然后我通过它,寻找一个特定的关键字,如果我找到了那个关键字。我将在 .csv 文件中写下与此相关的所有内容。

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

This is my write_light_csvfunction :

这是我的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']})

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

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

采纳答案by Igor Hatarist

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

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

Something like that:

类似的东西:

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']})

回答by eumiro

Can you change the structure of your code and export the whole file at once?

您可以更改代码结构并立即导出整个文件吗?

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

        writer.writeheader()

        for item in data:
            if "light" in item:
                writer.writerow({'TimeStamp': item['ts'], 'light' : item['light'],'Proximity' : item['prox']})


write_light_csv('light.csv', data)

回答by SIslam

I would use some flagand run a check before writing headers! e.g.

flag在写之前我会使用一些并进行检查headers!例如

flag=0
def get_data(lst):
    for i in lst:#say list of url
        global flag
        respons = requests.get(i)
        respons= respons.content.encode('utf-8')
        respons=respons.replace('\','')
        print respons
        data = json.loads(respons)
        fl = codecs.open(r"C:\Users\TEST\Desktop\data1.txt",'ab',encoding='utf-8')
        writer = csv.DictWriter(fl,data.keys())
        if flag==0:
            writer.writeheader()
        writer.writerow(data)
        flag+=1
        print "You have written % times"%(str(flag))
    fl.close()
get_data(urls)

回答by Gilbert

You can check if the file is empty

您可以检查文件是否为空

import csv
import os

headers = ['head1', 'head2']

for row in interator:
    with open('file.csv', 'a') as f:
        file_is_empty = os.stat('file.csv').st_size == 0
        writer = csv.writer(f, lineterminator='\n')
        if file_is_empty:
            writer.writerow(headers)
        writer.writerow(row)

回答by DeveScie

Just another way:

只是另一种方式:

with open(file_path, 'a') as file:
        w = csv.DictWriter(file, my_dict.keys())

        if file.tell() == 0:
            w.writeheader()

        w.writerow(my_dict)

回答by rearThing

You can use the csv.SnifferClass and

您可以使用csv.Sniffer类和

with open('my.csv', newline='') as csvfile:
    if csv.Sniffer().has_header(csvfile.read(1024))
    # skip writing headers