简体   繁体   中英

Concatenate rows of txt files with output to another txt file. Python

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

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:

Contents of the first file
$ python concatenate.py
Contents of the second file
 $ cat file2.txt Jhon WDC Starbucks 
Execute script
 $ python concatenate.py 
Contents of the output file
 $ cat file3.txt Hello how are u?:Jhon NYC:WDC Coffee Shop:Starbucks foo $ 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM