Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python csv,只写一次头文件_Python_Csv - Fatal编程技术网

python csv,只写一次头文件

python csv,只写一次头文件,python,csv,Python,Csv,所以我有一个从.Json创建CSV的程序 首先,我加载json文件 f = open('Data.json') data = json.load(f) f.close() 然后,我通过它,寻找一个特定的关键字,如果我找到那个关键字。我将把所有与此相关的内容都写在.csv文件中 for item in data: if "light" in item: write_light_csv('light.csv', item) 这是我的write\u light\u csv功能

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

首先,我加载json文件

f = open('Data.json')
data = json.load(f)
f.close()
然后,我通过它,寻找一个特定的关键字,如果我找到那个关键字。我将把所有与此相关的内容都写在.csv文件中

for item in data:
    if "light" in item:
       write_light_csv('light.csv', item)
这是我的
write\u light\u 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
,现在它每次写入时都会添加一个头。如何确保头只写入一次?

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

诸如此类:

导入操作系统路径
file_exists=os.path.isfile(文件名)
将open(filename,'a')作为csvfile:
标题=['TimeStamp','light','proximition']
writer=csv.DictWriter(csvfile,分隔符=',',行终止符='\n',字段名=标题)
如果文件不存在:
writer.writeheader()文件尚不存在,请写入头
writer.writerow({'TimeStamp':dic['ts'],'light':dic['light'],'proximition':dic['prox']})

您能否更改代码的结构并立即导出整个文件

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)

我会使用一些
标志
,并在写入
标题之前运行检查!e、 g

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)

您可以检查文件是否为空

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)
换一种方式:

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

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

        w.writerow(my_dict)
您可以使用类和

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

使用熊猫时:(用于将数据帧数据存储到CSV文件) 如果您使用索引来迭代API调用以在CSV文件中添加数据,只需在设置header属性之前添加此检查

if i > 0:
        dataset.to_csv('file_name.csv',index=False, mode='a', header=False)
    else:
        dataset.to_csv('file_name.csv',index=False, mode='a', header=True)

@Kos文件以前不会写入磁盘,而
中的
块中没有对file对象的操作,但是您是对的,这有点让人困惑。我更改了我的示例。@Kos对不起,你是对的,文件创建得更早。@igor,
file\u exists
,您不需要冒号:)@IgorHatarist非常感谢!非常感谢,它真的解决了我的问题