blackfury
blackfury

Reputation: 685

Join each line from two files as one line using python

I am trying to join lines of two files as one using python. Can anyone help me out on this:

File 1:

abc|123|apple

abc|456|orange

abc|123|grape

abc|123|pineapple

abc|123|mango

File 2:

boise

idaho

sydney

tokyo

london

Expected Output File:

abc|123|apple|boise
abc|456|orange|idaho
abc|123|grape|sydney
abc|123|pineapple|tokyo
abc|123|mango|london

**Code tried so far:**

    from itertools import izip
    with open('merged.txt', 'w') as res:
            with open('input1.txt') as f1:
                    with open('input2.txt') as f2:
                            for line1, line2 in zip(f1, f2):
                                    res.write("{} {}\n".format(line1.rstrip(), line2.rstrip()))

I am new to python, is there a simple way to append lines from two files with the separator '|'. Thanks in advance.

Upvotes: 2

Views: 236

Answers (2)

repzero
repzero

Reputation: 8412

A concise version will be like this

file1=[y.strip() for y in open("file01").readlines()] # read all lines
file2=["|"+x.strip() for x in open("file02").readlines()]  #read all lines but add a "|" at begining of line in file2 
mergedfile=zip(file1,file2) #combine lines
merged_file=open("a_new_file","w")
for line in mergedfile:
    merged_file.write(line[0]+line[1]+"\n") #combine lines
merged_file.close() #close "a_new_file"

Upvotes: 0

jeff carey
jeff carey

Reputation: 2373

Very close, just change the last line to:

res.write("{0}|{1}\n".format(line1.rstrip(), line2.rstrip()))

Upvotes: 2

Related Questions