Merge 3 Textfiles with python

152 views Asked by At

Im really new to programming and couldn´t find a satisfying answer so far. Im using python and I want to merge three textfiles receive all possible word combinations. I have 3 files:

First file:

line1
line2
line3

Second file(prefix):

pretext1
pretext2
pretext3

Third file(suffix):

suftext1
suftext2
suftext3

I already used .read() and have my variables containing the list for each textfile. Now I want to write a function to merge this 3 files to 1 and it should look like this:

outputfile:

pretext1 line1 suftext1 #this is ONE line(str)
pretext2 line1 suftext1
pretext3 line1 suftext1
pretext1 line1 suftext2
pretext1 line1 suftext3

and so on, you get the idea

I want all possible combinations in 1 textfile as output. I guess I have to use a loop within a loop?!

2

There are 2 answers

12
ysearka On BEST ANSWER

Here it is, if I got your question right. First you have to focus into the correct folder with the os package.

import os
os.chdir("The_path_of_the_folder_containing_the_files")

Then you open you three files, and put the words into lists:

file_1 = open("file_1.txt")
file_1 = file_1.read()
file_1 = file_1.split("\n")

file_2 = open("file_2.txt")
file_2 = file_2.read()
file_2 = file_2.split("\n")

file_3 = open("file_3.txt")
file_3 = file_3.read()
file_3 = file_3.split("\n")

You create the text you want in your output file with loops:

text_output = ""
for i in range(len(file_2)):
    for j in range(len(file_1)):
        for k in range(len(file_3)):
            text_output += file_2[i] + " " + file_1[j] + " " + file_3 [k] + "\n"

And you enter that text into your output file (if that file does not exist, it will be created).

file_output = open("file_output.txt","w")
file_output.write(text_output)
file_output.close()
0
Ian McLaird On

While the existing answer may be correct, I think this is a case where bringing in a library function is definitely the way to go.

import itertools

with open('lines.txt') as line_file, open('pretext.txt') as prefix_file, open('suftext.txt') as suffix_file:
    lines = [l.strip() for l in line_file.readlines()]
    prefixes = [p.strip() for p in prefix_file.readlines()]
    suffixes = [s.strip() for s in suffix_file.readlines()]

    combos = [('%s %s %s' % (x[1], x[0], x[2])) 
              for x in itertools.product(lines, prefixes, suffixes)]

    for c in combos:
        print c