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

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.


with open (saveAddr+".csv",'a') as allpckts:

will create a new file saveAddr+".csv" if not exist, otherwise open it for further appending.Assuming saveAddr is the file name(if path includes in it, check whether path exists.)

If you want to check file exists

os.path.isfile('/path/to/csv')

#check if dir exist if not create it
def check_dir(file_name):
    directory = os.path.dirname(file_name)
    if not os.path.exists(directory):
        os.makedirs(directory)


def save(file_name, records):
    check_dir(file_name)
    csv_file = open(file_name,'w+')
    csvWriter = csv.writer(csv_file,delimiter=',')
    count = 0
    for record in records:
        csvWriter.writerow([record])
        count+=1

    print(count, " record saved to ",file_name)
    return  count    enter code here

directory = os.path.abspath(os.path.join(os.path.curdir))
save(directory+"/data/filename.csv",your_list)