Finn Mainstone Finn Mainstone - 1 year ago 52
Python Question

Replacing cells in a column, but not header, in a csv file with python

I've been looking for a few hours now and not found what I'm looking for...

I'm looking to make a program that takes an already compiled .csv file with some information missing and asking the user what they would like to add and then placing this in the csv but not effecting the header line. Then saving the file with the additions.

It would look like (input):

data 1, data 2, data 3

program asks "what would you like in data 2 column?

answer: 5


data 1, data 2, data 3

All help highly appreciated.

Answer Source
  1. We open the input file and the output file with a python context manager.
  2. get the user input using input() (python 3) or raw_input() (python 2) functions
  3. grab the 1st row in the file and write it out without changing anything and write that out
  4. Loop through the rest of the file splitting the columns out and replacing column 2 with the user's input

    with open('in.csv', 'r') as infile, open('out.csv', 'w') as outfile:
        middle_col = input('What would you like in data 2 column>: ')
        outfile.write(infile.readline())  # write out the 1st line
        for line in infile:
            cols = line.strip().split(',')
            cols[1] = middle_col
            outfile.write(','.join(cols) + '\n')