Adding in-between column in csv Python
Question: I work with csv files and it seems python provides a lot of flexibility for
handling csv files.

I found several questions linked to my issue, but I cannot figure out how to
combine the solutions effectively...

My starting point CSV file looks like this (note there is only 1 column in the
'header' row):

    
    
    FILE1
    Z1 20 44 3
    Z1 21 44 5
    Z1 21 44 8
    Z1 22 45 10
    

What I want to do is add a column in between cols #1 and #2, and keep the rest
unchanged. This new column has the same # rows as the other columns, but
contains the same integer for all entries (10 in my example below). Another
important point is I don't really know the number of rows, so I might have to
count the # rows somehow first (?) My output should then look like:

    
    
    FILE1
    Z1 10 20 44 3
    Z1 10 21 44 5
    Z1 10 21 44 8
    Z1 10 22 45 10
    

Is there a simple solution to this?


Answer: I think the easiest solution would be to just read each row and write a
corresponding new row (with the inserted value) in a new file:

    
    
    import csv
    with open('input.csv', 'r') as infile:
         with open('output.csv', 'w') as outfile:
             reader = csv.reader(infile, delimiter=' ')
             writer = csv.writer(outfile, delimiter=' ')
             for row in reader: 
                 new_row = [row[0], 10]
                 new_row += row[1:]
                 writer.writerow(new_row)
    

This might not make sense if you're not doing anything else with the data
besides this bulk processing, though. You'd' want to look into csv libraries
if that were the case.

