Python – Add data to rows in csv file python

csvpython

I am trying to loop through an existing csv file in python and append a (different) value to the end of each row.

Code to read the lines of the file

out_file = open(outputfile, 'r+')
out_reader = csv.reader(out_file)
out_lines = [row for row in out_reader]

Code to append the new value

out_lines[i] = out_lines[i][0] + "\t %r " % lstName[0]

The problem is that I am getting the desired values in out_lines, but NOT in my original file. What's the best way to append these results to my original file, one row at a time?

Best Answer

If you don't want write the new data to a second file, you will need to overwrite the source in place.

From your code it seems that the input file has only 1 column and that the column delimiter is a tab character.

It's not clear where the new value to append to each row comes from, so I assume here that it is stored in a list (lstName) that contains at least as many elements as there are rows in the input file:

import csv

lstName = ['a', 'b', 'c', 'd', 'e', 'etc']

with open('file.csv', 'r+') as f:
    reader = csv.reader(f, delimiter='\t')
    out_lines = [row + [lstName[i]] for i, row in enumerate(reader)]
    f.seek(0)    # set file position to the beginning of the file
    csv.writer(f, delimiter='\t').writerows(out_lines)

First the file is read and a list constructed with the new value appended. enumerate() is used to provide an index into the lstName list. After the file has been read the file is repositioned to the start of the file and the new data is then written out to the file, overwriting the original file contents.