LearningGuy15
LearningGuy15

Reputation: 15

Concatenate two files in a loop to create new file?

I'm trying to combine two lists. They are both in files named list1.txt and list2.txt. I'm trying to append the words in list2.txt to list1.txt. For example:

list1.txt has thousands of words like

list2.txt has around a dozen words like

I'd like to get an output that takes all words from list2.txt and concatenate them to each word in list1.txt. So the output would look something like this:

etc. I'm not sure how to get this done. Any help is appreciated.

Upvotes: 0

Views: 463

Answers (4)

JashSmith
JashSmith

Reputation: 241

I think this may help you

List = []
list1 = open('list1.txt','r')
total = ''
for i in list1:
    List.append(i.strip())
list1.close()
for append_text in List:
    
    list2 = open('list2.txt','r')    
    for i in list2:
        final = str(append_text)+str(i)
        total = total+final
    total = total+'''\n'''
    list2.close()
print(total)

Upvotes: 1

Ismail Hafeez
Ismail Hafeez

Reputation: 740

You can use zip():

with open("output.txt", 'a') as output:
    with open('file1.txt') as file1, open('file2.txt') as file2:
        for word1, word2 in zip(file1, file2):
            output.write(word1 + word2 + "\n")

What this does is, it opens, parses through them together and writes it to an output file.

Edit: This question has been upvoted, so I think this worked for you, but looking again onto your question I saw that you require a different output. Here is the revised code:

output = open("output.txt", 'a')
file1 = open('file1.txt')
file2 = open('file2.txt')
for word in file1:
    for second_word in file2:
        output.write(word + second_word + "\n")
    file2.seek(0)
output.close()
file1.close()
file2.close()

For each word in file1 it iterates through all the words in file2 and adds them together. Then it moves on to the next word in file1 and so on.

Upvotes: 1

Tony Suffolk 66
Tony Suffolk 66

Reputation: 9724

I can't guarantee this will give you specific order but :

from itertools import product

with open("output.txt", 'w') as output:
    with open('file1.txt', 'r' ) as file1, open('file2.txt','r') as file2:
       for word1, word2 in product(file1, file2):
           output.write(word1.strip() + word2.strip() + "\n")

itertools.product() will give you every combination of words from the first file and words from the 2nd file.

Upvotes: 1

James Brown
James Brown

Reputation: 37464

Using join to get a cartesian product and tr to get rid of the delimiting space:

$ join -o 1.1,2.1 -j 666 file1 file2 | tr -d ' '

Some output:

applecrust
applelake
applerain
...

Solution is abusing the fact that there is no field 666 in the files and joining on a nonexisting field produces the cartesian product of the items in the files.

Upvotes: 3

Related Questions