89DEVs

How to append to an existing csv file in Python?

append to an existing csv file in python

How to append to an existing csv file in Python?

Instead of creating an empty csv file it is also possible to append to an existing csv file. This can be done by opening the csv file using the file mode parameter a. This brings the pointer to the end of the file instead of the beginning. So the new content will be appended to the end of the file, while the default mode replaces existing content. # how to append to an existing csv file with open('myCSV.csv','a') as fp: fp.write(myNewRow) The inserted variable myNewRow should consist of comma-separated values to be appended correctly to the csv file. Let's see how this works in a complete script, that opens an existing csv file and appends a new line. # append new line to existing csv file import csv newLine=['column1','column2','column3'] with open('myCSV.csv', 'a') as fp: writer = csv.writer(fp) writer.writerow(newLine) If we open the csv file, we can see that the newLine is appended to the end of the csv file. column1,column2,column3 column1,column2,column3 Python works with a lot of different file modes, while 'r' is the default mode we can specify the file mode that is best for our needs. In this case it is file mode 'a', but it is always good practice to know all the file modes available in Python. It is also important to remember that a file opened in file mode 'w' overwrites the content of the file, so be careful and make sure to use the right mode when working with csv files in Python.

                
        

Summary


Click to jump to section