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

时间:2016-09-27 06:47:18

标签: python

我是python的新手。我要做的是梳理文件' a'和文件' b'通过LINE进入LINE文件。

例如,

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

text file b = 1("\n")2("\n") 3

新文本文件将包含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)

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

2 个答案:

答案 0 :(得分:2)

积分:

  • 使用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)

x.txt的内容:

1
2
3

y.txt的内容:

a
b
c

z.txt的内容:

a 1
b 2
c 3

带拉链功能的代码:

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()))

答案 1 :(得分:0)

阅读有关文件处理和有效使用内置函数的更多信息。 对于您的查询,仅使用h1 = f2+g2不是方法。

a=open('a.txt','r').readlines()
b=open('b.txt','r').readlines()
with open('z.txt','w') as out:
    for i in range(0,10): #this is for just denoting the lines to join.
         print>>out,a[i].rstrip(),b[i]