pythonstringline

How to multiply lines from two different text files into one text file in Python?


How to multiply lines from two different text files into one text file in Python?

file 1 file 2
zzzzzz bbbbbb
aaaaaa ffffff
nnnnnn kkkkkk

I would like the result sequence to be as follows

| result |
| zzzzzzbbbbbb |
| zzzzzzffffff |
| zzzzzzkkkkkk |
| aaaaaabbbbbb |
| aaaaaaffffff |
| aaaaaakkkkkk |
| nnnnnnbbbbbb |
| nnnnnnffffff |
| nnnnnnkkkkkk |

I'm tired trying to make this code or find something similar, so many thanks to anyone who helps me with the solution.

def write_files(files):
    opened_files = []
    for f in files:
        opened_files.append(open(f, "r"))

    output_file = open("result.txt", "w")
    num_lines = sum(1 for line in opened_files[0])
    opened_files[0].seek(0,0)
    for i in range(num_lines):
        line = [of.readline().rstrip() for of in opened_files]
        line = " ".join(line)
        line += "\n"
        output_file.write(line)
    for of in opened_files:
        of.close()
    output_file.close()

write_files(["1.txt", "2.txt"])

Solution

  • The easy way is to use itertools.product:

    import itertools
    
    def write(files):
        data = [ open(f).read().splitlines() for f in files]
        return [''.join(t) for t in itertools.product(*data)]
    
    print('\n'.join(write(['f1.txt','f2.txt'])))
    

    Output:

    zzzzzzbbbbbb
    zzzzzzffffff
    zzzzzzkkkkkk
    aaaaaabbbbbb
    aaaaaaffffff
    aaaaaakkkkkk
    nnnnnnbbbbbb
    nnnnnnffffff
    nnnnnnkkkkkk
    

    Note, however, that the list grows really big very quickly.