user6886108 user6886108 - 1 year ago 155
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

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

Answer Source

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]

Content of x.txt:


Content of y.txt:


Content of z.txt:

a 1
b 2
c 3
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download