Search code examples
pythonlistioconcatenation

Python append line of strings to other line of strings


I'm new in Pyhton so please don't be hard to me. I'm try to get a file called results.txt which should contain strings from two different files. I have a file called:

to-read.txt:

api.domain.com
domain.com
www.domain.com

and a file called:

to-add.txt:

api
www
account
prod
test
temp

now I'm try to add for every string in to-read.txt the words from to-add.txt but at the beginning. for example for the api.domain.com then I sould get:

api.api.domain.com
www.api.domain.com
account.api.domain.com
prod.api.domain.com
test.api.domain.com
temp.api.domain.com

and so on for the other in to-read.txt. My code looks like this:

f = open("results.txt", "w")
with open("to-read.txt", "r") as r, open("to-add.txt", "r") as a:

    for read in r:
        data = read.strip()
        print(data)

    for word in a:
        words = word.strip()
        print(words)



f.close()

Now I don't know how to append to-add with to-read and save it to results.txt


Solution

  • Use:

    with open("to-read.txt") as domains,\
            open("to-add.txt") as prefixes,\
            open("results.txt", "w") as output:
        for d in domains:
            for p in prefixes:
                output.write(f"{p.strip()}.{d.strip()}\n")
    
            prefixes.seek(0)
    

    The contents of results.txt file should look like:

    api.api.domain.com
    www.api.domain.com
    account.api.domain.com
    prod.api.domain.com
    test.api.domain.com
    temp.api.domain.com
    api.domain.com
    www.domain.com
    account.domain.com
    prod.domain.com
    test.domain.com
    temp.domain.com
    api.www.domain.com
    www.www.domain.com
    account.www.domain.com
    prod.www.domain.com
    test.www.domain.com
    temp.www.domain.com