append new row to old csv file python
Solution 1:
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.
Solution 2:
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.
Solution 3:
Based in the answer of @G M and paying attention to the @John La Rooy's warning, I was able to append a new row opening the file in 'a'
mode.
Even in windows, in order to avoid the newline problem, you must declare it as
newline=''
.Now you can open the file in
'a'
mode (without the b).
import csv
with open(r'names.csv', 'a', newline='') as csvfile:
fieldnames = ['This','aNew']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writerow({'This':'is', 'aNew':'Row'})
I didn't try with the regular writer (without the Dict), but I think that it'll be ok too.