Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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 ..

like image 660
Dop3n Avatar asked Nov 28 '25 00:11

Dop3n


2 Answers

Points :

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

Code without zip 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

Code with zip function:

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()))
like image 109
Dinesh Pundkar Avatar answered Nov 29 '25 16:11

Dinesh Pundkar


Read more about file handling and using the in-built functions efficiently. For your query just using h1 = f2+g2 is not the way.

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]
like image 43
Siva Shanmugam Avatar answered Nov 29 '25 14:11

Siva Shanmugam