Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python combine two text files to one file

Tags:

python

i want to create a simple code to combine two text files , example file1.txt contain:

car
house

and file2.txt contain :

voiture
maison

i want to combine the lines of the two files and separte them by ':' to look like that :

car:voiture 
house:maison 

i try to do it and i'm sure that i'm wrong anyway i will post my code :) :

with open("user.txt") as u: 
 with open("site.txt") as s:
     for line in s.read().split('\n'):
      s1=line
      for line in u.read().split('\n'):
       s2=line
       with open('result.txt', 'a') as file:
        file.write(s1+':'+s2)

and thanks a lot for any help guys :)


2 Answers

This is a use case for itertools.izip:

from itertools import izip

with open('file1.txt') as f1, open('file2.txt') as f2, open('new.txt', 'w') as fout:
    for fst, snd in izip(f1, f2):
        fout.write('{0}:{1}\n'.format(fst.rstrip(), snd.rstrip()))

This combines the first line from the first file with the first line from the second file (then the second line from the first file with the second line from the second file etc...), removes newlines from the lines, adds a : in the middle and adds a \n so it's actually a line. This saves loading both files fully into memory and does it iteratively over each. Note though, that if the files are not of equal length, the result will stop at the number of lines in the shortest file.

like image 79
Jon Clements Avatar answered May 01 '26 00:05

Jon Clements


Your code won't work because you try to read the whole second file for every line in the first one, also, there are a few other bugs (like not writing newlines, etc.). Try instead

with open("user.txt") as u, \
     open("site.txt") as s, \
     open("result.txt", "a") as file: # Only open every file once for all output 
     for s1 in u: # You don't nead to use .read().split('\n')
         s2 = s.readline() # Read ONE line INCLUDING the newline char
         file.write(s1 + ":" + s2) # Write output with the newline from `s2`

Or, you could just read all lines and use zip:

with open("user.txt") as u, \
     open("site.txt") as s, \
     open("result.txt", "a") as file:
     user_lines = u.readlines()
     size_lines = s.readlines()
     for s1, s2 in zip(user_lines, size_lines):
         file.write(s1 + ":" + s2 + "\n") # Write output with newline char
like image 25
hlt Avatar answered May 01 '26 00:05

hlt