Python] 将两个文本文件合二为一(逐行)

Dop*_*p3n 1 python

我是python的新手。我想要做的是将文件 'a' 和文件 'b' 合并成一个文件 LINE 一个 LINE。

例如,

text file a = a ("\n") b("\n") c

text file b = 1("\n")2("\n") 3
Run Code Online (Sandbox Code Playgroud)

新的文本文件将包含 a 1("\n") b 2("\n") c 3

def main():
  f1 = open("aaa.txt")
  f2 = f1.readlines()
  g1 = open("bbb.txt")
  g2 = g1.readlines()
  h1 = f2+g2
  print(h1)
Run Code Online (Sandbox Code Playgroud)

很抱歉这是我第一次使用 stackoverflow ..

Din*_*kar 7

积分:

  • 使用with.打开文件。无需关闭文件。
  • 使用zip函数组合两个列表。

带有内联注释的不带 zip 的代码:

combine =[]

with open("x.txt") as xh:
  with open('y.txt') as yh:
    with open("z.txt","w") as zh:
      #Read first file
      xlines = xh.readlines()
      #Read second file
      ylines = yh.readlines()
      #Combine content of both lists
      #combine = list(zip(ylines,xlines))
      #Write to third file
      for i in range(len(xlines)):
        line = ylines[i].strip() + ' ' + xlines[i]
        zh.write(line)
Run Code Online (Sandbox Code Playgroud)

x.txt 的内容:

1
2
3
Run Code Online (Sandbox Code Playgroud)

y.txt 的内容:

a
b
c
Run Code Online (Sandbox Code Playgroud)

z.txt 的内容:

a 1
b 2
c 3
Run Code Online (Sandbox Code Playgroud)

带有 zip 功能的代码:

with open("x.txt") as xh:
  with open('y.txt') as yh:
    with open("z.txt","w") as zh:
      #Read first file
      xlines = xh.readlines()
      #Read second file
      ylines = yh.readlines()
      #Combine content of both lists  and Write to third file
      for line1, line2 in zip(ylines, xlines):
        zh.write("{} {}\n".format(line1.rstrip(), line2.rstrip()))
Run Code Online (Sandbox Code Playgroud)