0

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
2,,4
4,,6
6,,3
3,,2

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

answer: 5

(output):

data 1, data 2, data 3
2,5,4
4,5,6
6,5,3
3,5,2

All help highly appreciated.

2 Answers2

1
  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')
  • that's great Thanks! Not exactly sure how the last line works - but it does, the bits before I've stolen from other areas already. Thank you so much for your help! :) – Finn Mainstone Jul 22 '16 at 18:33
  • The last line takes each element of the list cols and joins them together into a string using a comma as the separator. It also re-adds a newline which was stripped off in the 1st line in the for in loop. – Nathanael Huffman Jul 23 '16 at 01:18
0

I believe the main part of your question (how to skip the header) has been answered here:

Skip the headers when editing a csv file using Python

If you call next() on the reader once, the first row (the header) will be skipped. Then you can do for row in reader like usual.

Community
  • 1
  • 1
  • Thanks for the feedback - you're totally right the header bit was sort of solved I'm just a little stumped at the best way to write to the cells below in the column but it's working nicely now. Thanks! – Finn Mainstone Jul 22 '16 at 18:36