Jonathan Shobrook Jonathan Shobrook - 1 year ago 133
Python Question

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

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


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

Answer Source

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')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download