Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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) 
like image 657
alphiii Avatar asked Aug 19 '15 06:08

alphiii


1 Answers

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.

like image 184
Anand S Kumar Avatar answered Sep 27 '22 23:09

Anand S Kumar