1

我想根据另一个文本文件中的值替换文本文件中的列。我跳过了前 3 个标题行并将 file1 中的第二列读入列表 L 并希望替换 file2 中的第 2 列。以下是我所拥有的:

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

例如:

L = ['2.3','1.2']

和文本文件是:

 x     y    z
1.1   2.1  1.4
1.9   1.8  2.1

我想用列表 L 值替换变量 y 下的值。任何建议将不胜感激。

4

2 回答 2

1

这是一种方法,假设列表中的元素数量与文件中的行数相同。还假设您想要元素之间的选项卡。还假设“第 2 列”表示第二列,python 索引为 1。最终假设,您只想将替换的文件打印到屏幕上。在 OSX 或 Linux 上,您可以通过> editedfile.txt在命令后面添加来捕获编辑的文件。如果有四列或更多列,只需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])

输出(其中中间值已更改为2.3and 1.2,并且我用空格替换了制表符以进行格式化):

 x     y    z
1.1    2.3    1.4
1.9    1.2    2.1
于 2013-11-06T07:51:41.253 回答
0

可能需要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
于 2013-11-05T23:17:27.817 回答