Peter Chao Peter Chao - 1 year ago 70
Python Question

what file mode to create new when not exists and append new data when exists

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.

My code:

def main():
list1 = [ 'DATE','DATASET','name1','name2','name3']
dict1 =dict.fromkeys(list1,0)
with open('masterResult.csv','w+b')as csvFile:
header = next(csv.reader(csvFile))
dict_writer = csv.DictWriter(csvFile,header,0)

if __name__ =='__main__':

Answer Source

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
 if(os.path.exists(filename) and os.path.isfile(filename)):
 if(filesize == 0):
    f.write('%s\n' % header)
 f.write('%s\n' % 'name1,25')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download