Appending writes data to the end of a file, not to the end of each row.
Instead, create a new file and append the new value to each row.
csvfile = 'filename'
with open(csvfile, 'r') as fin, open('new_'+csvfile, 'w') as fout:
reader = csv.reader(fin, newline='', lineterminator='
')
writer = csv.writer(fout, newline='', lineterminator='
')
if you_have_headers:
writer.writerow(next(reader) + [new_heading])
for row, val in zip(reader, data)
writer.writerow(row + [data])
On Python 2.x, remove the newline=''
arguments and change the filemodes from 'r'
and 'w'
to 'rb'
and 'wb'
, respectively.
Once you are sure this is working correctly, you can replace the original file with the new one:
import os
os.remove(csvfile) # not needed on unix
os.rename('new_'+csvfile, csvfile)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…