views:

91

answers:

2

Hi

I wish to add a column of data to a file.

The file currently has three tab delimited columns.

abbd    1234    0.987
affr    2345    0.465

I have a list of length 8,800 comprising floats.

li = [-1.0099876, 34.87659]

I wish to add this list as a fourth column to the file.

abbd    1234    0.987    -1.0099876

Note - my file is open in r+ mode.

Thanks, S :-)

+3  A: 
import fileinput

for fl, line in zip(li, fileinput.input(['a.txt'], inplace=True)):
    print(line.strip() + '\t' + str(fl))
SilentGhost
+1  A: 

I'm with MattH, in-place operations are usually a bad idea. The alternative approach could be:

import itertools

def add_column(lines, values, column_delimiter="\t"):
    for line, value in itertools.izip(lines, values):
        yield line.rstrip() + column_delimiter + str(value)

li = [-1.0099876, 34.87659]  
for line in add_column(open("a.txt"), li):
    print line
tokland