首页 > 解决方案 > 如何将两个文本文件合并为一个?

问题描述

我有两个文本文件。我想将他们的一些列合并到一个新的文本文件中。

我正在尝试这个,但它不起作用:

with open('1','r') as first:
    with open('2', 'r') as second:
        data1 = first.readlines()
        for line in data1:
            output = [(item.strip(), line.split(' ')[2]) for item in second]
            f = open("1+2","w")
            f.write("%s  %s\n" .format(output))
            f.close()

我拥有的第一个文本文件:

1
2
3
4

我拥有的第二个文本文件:

1 3
2 5
5 7
7 3

我想要一个新文件,其中第一个文件中的列和第二个文件中的第二列,如下所示:

1 3
2 5
3 7
4 3

标签: pythontext

解决方案


您可以遍历相应的行对,并将第一个文件的第一列与第二个文件的第二列连接起来:

with open('file_1.txt') as f1, open('file_2.txt') as f2, open('new_file.txt', 'w') as fr:
    for line in ("{} {}".format(l1.rstrip('\n'), l2.split(maxsplit=1)[1]) for l1, l2 in zip(f1, f2)):
        fr.write(line)

如果您确定列由单个空格分隔,您还可以使用str.partition如下:

l2.partition(' ')[-1]

例子:

In [28]: with open('file_1.txt') as f1, open('file_2.txt') as f2, open('new_file.txt', 'w') as fr:
    ...:     for line in ("{} {}".format(l1.rstrip('\n'), l2.split(maxsplit=1)[1]) for l1, l2 in zip(f1, f2)):
    ...:         fr.write(line)
    ...:     

In [29]: cat new_file.txt
1 3
2 5
3 7
4 3

顺便说一句,当您在两个文件中没有相同数量的行,并且您想继续对最长的行进行操作时,您可以查看itertools.zip_longest而不是zip.


推荐阅读