append new row to old csv file python
append new row to old csv file python
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.
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(rname, 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.
append new row to old csv file python
Based in the answer of @G M and paying attention to the @John La Rooys 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(rnames.csv, a, newline=) as csvfile:
fieldnames = [This,aNew]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writerow({This:is, aNew:Row})
I didnt try with the regular writer (without the Dict), but I think that itll be ok too.