0
votes

I am new to Python and I am trying to concatenate the rows of one file1.txt with another file2.txt and its output must be to another file3.txt For example:

file1.txt:

Hello how are u?:

NYC: 

Coffee Shop:

File2.txt:

Jhon 

WDC 

Starbucks

The output should be:

file3.txt:

Hello how are u?: Jhon 

NYC: WDC

Coffe Shop: Starbucks

I have this:

 from io import open
 input1=open("file1.txt","r",encoding="utf-8")
 input2=open("file2.txt","r",encoding="utf-8")
 output=open("file3.txt","w",encoding="utf-8")

 file1=input1.readlines()
 file2=input2.readlines()

 j=0
 for i in ingles:
    out=file1[j]+":"+file2[j]
    j=j+1
    output.writelines(out)

input1.close()
input2.close()
output.close()

It create the file but it does not concatenate the result in the same row...

2
what is for i in ingles supposed to be doing?dbmitch

2 Answers

0
votes

All the lines both in file1 and file2 contains '\n' at the end. Use strip() to remove it: out=file1[j].strip()+":"+file2[j]

0
votes

This implementation handles files that are not equal line length.

#!/usr/bin/python

from __future__ import print_function

FILE_A = './file1.txt'
FILE_B = './file2.txt'
OUTPUT = './file3.txt'

with open(FILE_A, 'r') as file_a, open(FILE_B, 'r') as file_b:
    with open(OUTPUT, 'w') as out:
        for a, b in map(None, file_a.readlines(), file_b.readlines()):
            a = a.rstrip() if a is not None else ''
            b = b.rstrip() if b is not None else ''
            print('%s%s' % (a, b), file=out)

Usage:

$ cat file1.txt
Hello how are u?:

NYC:

Coffee Shop:
foo
$ cat file2.txt
Jhon

WDC

Starbucks
$ python concatenate.py
$ cat file3.txt
Hello how are u?:Jhon

NYC:WDC

Coffee Shop:Starbucks
foo
$