user6886108 user6886108 - 2 months ago 12
Python Question

Python] combine two text files into one (line by line)

I'm new to python. What I'm trying to do is combing file 'a' and file 'b' into one file LINE by LINE.

For example, text file a = a ("\n") b("\n") c [text file b = 1("\n")2("\n") 3]`

text file new will contain

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)


I'm so sorry this is my first time using stackoverflow ..

Answer

Points :

  • Open file using with. No need to close file.
  • Use zip function to combine two list.

Code with comments inline:

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)

Content of x.txt:

1
2
3

Content of y.txt:

a
b
c

Content of z.txt:

a 1
b 2
c 3
Comments