Search code examples
pythonpython-itertools

itertools write to multiple files and on separate lines


I have this script that make multiple combinations of words:

import itertools
from itertools import combinations_with_replacement

list = ['Mark', 'Jones', 'Albert', 'Mary', 'Bob']

combs = itertools.combinations_with_replacement(list, 5)

for item in combs:    
    print(item)
    with open('output{0}.txt', 'a') as f:
        f.writelines(item)

The problem is that the output file has no spaces between words and all words are on the same line, I tried multiple solutions but non worked. Also I tried to write every 10 iterations in a separate file but couldn't find a solution for that as well

I would really appreciate any suggestions

Thanks

this is how the output file looks like

MarkMarkMarkMarkMarkMarkMarkMarkMarkJones

Here is what it is supposed to look like

Mark Mark Mark Mark Mark
Mark Mark Mark Mark Jones

Solution

    • use the join method to concatenate the words in each combination with a space in between.
    • add a newline character \n at the end of each line to ensure that each combination is written on a separate line in the output file.
    import itertools
    
    my_list = ['Mark', 'Jones', 'Albert', 'Mary', 'Bob']
    
    combs = itertools.combinations_with_replacement(my_list, 5)
    
    with open('output.txt', 'a') as f:
        for item in combs:
            line = ' '.join(item) + '\n'
            print(line)
            f.write(line)
    

    you can use a counter variable to keep track of the number of iterations and create a new file every 10 iterations.

    import itertools
    
    my_list = ['Mark', 'Jones', 'Albert', 'Mary', 'Bob']
    
    combs = itertools.combinations_with_replacement(my_list, 5)
    
    counter = 0
    file_counter = 1
    
    for item in combs:
        counter += 1
        line = ' '.join(item) + '\n'
        print(line)
        
        with open(f'output{file_counter}.txt', 'a') as f:
            f.write(line)
        
        if counter == 10:
            counter = 0
            file_counter += 1
    
    • counter variable that keeps track of the number of iterations & After writing each combination to the current file, the counter is incremented.
    • When the counter reaches 10, a new file is created by incrementing the file_counter variable. This process repeats until all combinations are processed.