I need to do the following:
(1) create a csv file if it does not exist, append data if it exists
(2) when create a new csv file, created with heading from dict1.
list1 = [ 'DATE','DATASET','name1','name2','name3']
with open('masterResult.csv','w+b')as csvFile:
header = next(csv.reader(csvFile))
dict_writer = csv.DictWriter(csvFile,header,0)
if __name__ =='__main__':
I've written the below sample code which you can refer and use for your requirement. First of all, if you use, append mode for opening file, you can append if the file exists and newly write if it does not exist. Now, coming to your header writing, you can check the size of the file in prior. If the size is zero, then it is a new file obviously and you can write your header first. If the size is not zero, then you can append only data records without writing header. Below is my sample code. For the first time when you run it, it will create file with header. The next time you run the code, it will append only the data records and not the header.
import os header='Name,Age' filename='sample.csv' filesize=0 if(os.path.exists(filename) and os.path.isfile(filename)): filesize=os.stat(filename).st_size f=open(filename,'a') if(filesize == 0): f.write('%s\n' % header) f.write('%s\n' % 'name1,25') f.close()