sam
sam

Reputation: 655

Python merger data from two text files and storing it in a seprate text file

I have 2 text files named text1.txt and text2.txt with the following data:-

text1.txt
1
2
3
4
5

text2.txt
sam
Gabriel
Henry
Bob
Bill

I want to write a python scripting reading both the text files and displaying/writing the result in a third text filed, lets call it result.txt in the following format:-

1@sam
2@Gabriel
3@Henry
4@Bob
5@Bill

So I want the data to be merged together separated by '@' in result.txt.

Any Help?Thanks

Upvotes: 1

Views: 100

Answers (3)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250941

This works, and unlike other answers I am not reading all the lines into memory here:

from itertools import izip
with open('text1.txt') as f1:
    with open('text2.txt') as f2:
        with open('out.txt', 'w') as out:
            for a, b in izip(f1, f2):
                out.write('{0}@{1}'.format(a.rstrip(), b))
...                 
>>> !cat out.txt
1@sam
2@Gabriel
3@Henry
4@Bob
5@Bill

Upvotes: 1

shaktimaan
shaktimaan

Reputation: 12092

Here you go. Code comments in line:

data_one = []
data_two = []

# Open the input files for reading
# Open the output file for writing
with open('text1.txt') as in1_file, open('text2.txt') as in2_file, open('ouput') as o_file:

    # Store the data from the first input file
    for line in in1_file:
        data_one.append(line.strip())
    data_one = (a for a in data_one)

    # Store the data from the second input file
    for line in in2_file:
        data_two.append(line.strip())
    data_two = (a for a in data_two)

    # Combine the data from both the sources
    # and write it to the output file
    for a, b in zip(data_one, data_two):
        o_file.write('{0}@{1}'.format(a, b))

EDIT:

For python 2.7 and earlier, multiple with statement with multiple context managers are used as:

with open('text1.txt') as in1_file:
    with open('text2.txt') as in2_file:
        with open('ouput') as o_file:

Upvotes: 1

Bogdan Iulian Bursuc
Bogdan Iulian Bursuc

Reputation: 2275

This should be your answer:

with open('text1.txt', 'r') as t1, open('text2.txt', 'r') as t2:
    with open('text3.txt', 'w') as t3:
        for row in zip(t1.readlines(), t2.readlines()):
            t3.writeline("%s@%s" % row)

Upvotes: 0

Related Questions