How to create a CSV file if it does not exist and then only append to it Python

alphiii picture alphiii · Aug 19, 2015 · Viewed 26.7k times · Source

I want to know how to create a file if it does not exist in the directory. I want to only append data.

I am getting this error in Python: No such file or directory.

This is my code:

with open (saveAddr+".csv",'a') as allpckts:                            
    writer = csv.DictWriter(allpckts, delimiter=',', fieldnames=header) 
    if pktnum < 2:                                                        
        writer.writerow(dict((fn,fn) for fn in header))                 
        writer.writerow(packet_data)                                    
    else:                                                               
        writer.writerow(packet_data)    

Update: My problem was that I wasn't in right directory. So for anyone searching for the most basic syntax to only append to CSV file is:

with open (filename+".csv",'a') as filedata:                            
    writer = csv.DictWriter(filedata, delimiter=',', fieldnames=header)
    writer.writerow(data) 

Answer

Anand S Kumar picture Anand S Kumar · Aug 19, 2015

Most probably you are trying to create a file in a directory which does not exist .

What you want is what 'a' mode does , it creates the file if it does not exist , otherwise it appends to the file . But it would not create the directories , if those directories so not exist , you should create the directories used in saveAddr , before running the program .

If you want a programmatic solution , you can check out os.mkdir , which should create the directory.