简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM