Ibe
Ibe

Reputation: 6035

How to replace a column in a text file using a list?

I want to replace a column in a text file based on values from another text file. I skipped first 3 header lines and read second column from file1 into a list L and want to replace column 2 in file2. Following is what I have:

L = []
for index, line in enumerate(open("C:/file1.txt", "r")):
    if index <= 2:
        continue
    else:
        L.append(line.split()[1])

For example:

L = ['2.3','1.2']

and text file is:

 x     y    z
1.1   2.1  1.4
1.9   1.8  2.1

I want to replace values under variable y with list L values. Any suggestions would be appreciative.

Upvotes: 1

Views: 2835

Answers (2)

beroe
beroe

Reputation: 12316

Here is one way to do it, assuming there are the same number of elements in the list as there are lines in the file. Also assuming that you want tabs between the elements. Also assuming that "column 2" means the second column, with python index 1. Final assumption, you just want to print the substituted file to the screen. On OSX or Linux, you can capture the edited file by putting > editedfile.txt after the command. If there are four or more columns, just put elements[2:] instead of elements[2]:

# This must have the same number of values as lines in the file
L = ['2.3','1.2']
with open("file1.txt", "r") as f:
    # skip the first line but output it?
    print f.readline().rstrip('\n') 

    for value,line in zip(L,f):
        elements = line.split()
        print "{}\t{}\t{}".format(elements[0],value,elements[2])

Output (in which the middle values have been changed to 2.3 and 1.2, and I replaced the tabs wth spaces for formatting):

 x     y    z
1.1    2.3    1.4
1.9    1.2    2.1

Upvotes: 1

alko
alko

Reputation: 48317

You probably need itertools.izip or itertools.izip_longest:

import itertools
with open(fname1) as f1, open(fname2) as f2:
    for line1, line2 in itertools.izip(f1, f2):
        pass # some computations here

Upvotes: 0

Related Questions