简体   繁体   English

如何使用列表替换文本文件中的列?

[英]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. 我跳过了前3个标题行,并将文件1的第二列读入列表L,并希望替换文件2中的列2。 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. 我想用列表L值替换变量y下的值。 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. 还要假设“第2列”表示第二列,其python索引为1。 On OSX or Linux, you can capture the edited file by putting > editedfile.txt after the command. 在OSX或Linux上,可以通过在命令后放置> editedfile.txt来捕获编辑的文件。 If there are four or more columns, just put elements[2:] instead of elements[2] : 如果有四列或更多列,则只需放置elements[2:]而不是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): 输出(中间值已更改为2.31.2 ,我替换了带有空格的制表符进行格式化):

 x     y    z
1.1    2.3    1.4
1.9    1.2    2.1

You probably need itertools.izip or itertools.izip_longest : 可能需要itertools.izipitertools.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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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