Jonathan Shobrook Jonathan Shobrook - 3 months ago 18
Python Question

Adding a column to existing csv file as an array (Python)

Have a csv file called 'data.csv' in the following format:

test1,test2,test3
1,2,3
4,5,6
7,8,9


Given a list in the format ['test4', 4, 7, 10], how can I create a new csv file 'adjusted.csv' with all the data from data.csv and the added column like so:

test1,test2,test3, test4
1,2,3,4
4,5,6,7
7,8,9,10

Answer

read lines in

with open('data.csv', 'r') as fi:
    lines = [[i.strip() for i in line.strip().split(',')] \
             for line in fi.readlines()]

col = ['test4', 4, 7, 10]

Concatenate each row with corresponding element of col. Using enumerate to help keep track of which list index to use.

new_lines = [line + [str(col[i])] for i, line in enumerate(lines)]

Output to file

with open('adjusted.csv', 'w') as fo:
    for line in new_lines:
        fo.write(','.join(line) + '\n')