1

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.

3
  • What do you mean by "column"? Commented Nov 6, 2013 at 3:08
  • @Rob: I have edited OP to show the column. Commented Nov 6, 2013 at 7:39
  • 1
    consider using pandas package it might save you lot of time and efforts Commented Nov 6, 2013 at 11:26

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

3 Comments

That isn't valid Python. Did you mean with open(fname1) as f1, open(fname2) as f2:?
Also, you probably want to zip up the file objects, not the filenames.
yeah, don't have interpreter at hand, programm on paper. thanx!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.