append new row to old csv file python

StackOverflow

I am trying to add a new row to my old csv file. Basically, it gets updated each time I run the Python script.

Right now I am storing the old csv rows values in a list and then deleting the csv file and creating it again with the new list value.

Wanted to know are there any better ways of doing this.

Answer rating: 291

with open("document.csv","a") as fd:
    fd.write(myCsvRow)

Opening a file with the "a" parameter allows you to append to the end of the file instead of simply overwriting the existing content. Try that.

Answer rating: 204

I prefer this solution using the csv module from the standard library and the with statement to avoid leaving the file open.

The key point is using "a" for appending when you open the file.

import csv   
fields=["first","second","third"]
with open(r"name", "a") as f:
    writer = csv.writer(f)
    writer.writerow(fields)

If you are using Python 2.7 you may experience superfluous new lines in Windows. You can try to avoid them using "ab" instead of "a" this will, however, cause you TypeError: a bytes-like object is required, not 'str' in python and CSV in Python 3.6. Adding the newline="", as Natacha suggests, will cause you a backward incompatibility between Python 2 and 3.





Tutorials