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?.
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.
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.
To read CSV file without header, use the header parameter and set it to “None” in the read_csv() method.
has_header = csv. Sniffer(). has_header(csv_test_bytes) # Check to see if there's a header in the file.
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']})
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With