Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python csv, writing headers only once

Tags:

python

csv

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

First I load the json file.

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.

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

This is my write_light_csv function :

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 a and now every time it writes, it adds a header. How do I make sure that header is only written once?.

like image 548
cyberbemon Avatar asked Feb 04 '15 15:02

cyberbemon


People also ask

How do I stop repeating header when writing CSV?

Create an if condition to check for the need for writing headers. If headers exist no need to write headers. Empty/new CSV = write headers and you can leave out the writing header from that point on. I've gone ahead and added a section that will answer your loop question.

How do I add a header to a CSV file in Python?

In this article, we are going to add a header to a CSV file in Python. Method #1: Using header argument in to_csv() method. Initially, create a header in the form of a list, and then add that header to the CSV file using to_csv() method. The following CSV file gfg.

How do I skip a header in CSV?

To read CSV file without header, use the header parameter and set it to “None” in the read_csv() method.

How do I check if a CSV file has a header in Python?

has_header = csv. Sniffer(). has_header(csv_test_bytes) # Check to see if there's a header in the file.


2 Answers

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

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']}) 
like image 100
Igor Hatarist Avatar answered Sep 23 '22 09:09

Igor Hatarist


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) 
like image 33
SpiralDev Avatar answered Sep 26 '22 09:09

SpiralDev