Python 文本文件比较和连接

Python Text File Compare and Concatenate

我需要有关基于常用字符串连接两个文本文件的帮助。

我的第一个 txt 文件是这样的:

Hello abc
Wonders xyz
World abc

我的第二个 txt 文件如下所示:

abc A
xyz B
abc C

我希望我的输出文件是:

Hello abc A
Wonders xyz B
World abc C

我的代码是这样的:

a = open("file1","r")
b = open("file2","r")
c = open("output","w")

for line in b:
  chk = line.split(" ")

  for line_new in a:
     chk_new = line_new.split(" ")

     if (chk_new[0] == chk[1]):
        c.write(chk[0])
        c.write(chk_new[0])
        c.write(chk_new[1])

但是当我使用这段代码时,我得到的输出是:

Hello abc A
Wonders xyz B
Hello abc C

第 3 行不匹配。我应该怎么做才能以正确的方式获得它?

open 流不安全,您只能读取一个文件一次。这样做:

aLines = []
bLines = []

with open("file1","r") as a:
    for line in a:
        aLines.append(line.strip().split(" "))

with open("file2","r") as b:
    for line in b:
        bLines.append(line.strip().split(" "))

bLines.reverse()

with open("output","w") as c:
    for chk in aLines:
        chk_new = bLines.pop()
        if chk_new[0] == chk[1]:
            c.write(chk[0])
            c.write(chk_new[0])
            c.write(chk_new[1])

恐怕你误会了,你的代码并没有产生你所说的输出。

部分原因是文件只能读取一次,除非您将读取光标移回文件开头(file.seek(0)docs)。

部分原因是第一个文件中一行的第二个元素以换行符结尾,因此您正在比较例如"abc""abc\n" 等永远不会是真的。

因此输出文件将完全为空。

那么你是怎么解决这个问题的呢?多次读取一个文件似乎过于复杂,不要那样做。我建议你按照以下方式做一些事情:

# open all the files simultaneously
with open('file1', 'r') as (f1
  ), open('file2', 'r') as (f2
  ), open('output', 'w') as (outf
  ):
    lines_left = True

    while lines_left:
        f1_line = f1.readline().rstrip()

        # check if there's more to read
        if len(f1_line) != 0:

            f1_line_tokens = f1_line.split(' ')

            # no need to strip the line from the second file
            f2_line_tokens = f2.readline().split(' ')

            if f1_line_tokens[1] == f2_line_tokens[0]:
                outf.write(f1_line + ' ' + f2_line_tokens[1])
        else:
            lines_left = False

我已经在您的示例输入上对其进行了测试,它生成了正确的输出(其中 file1 是第一个示例文件,file2 是第二个示例文件)。如果我们谈论大文件(数百万行),这个版本将比 aarons 快得多。在其他情况下,性能差异可以忽略不计。