Python Forum

Full Version: writelines only writes one line to file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i have a somewhat simple question, that seems to be escaping me. i was messing around with the built-in method itertools to see if i could get anagrams of my name, anyway.. i wanted to write the results out to a file but i only get oneline written out. i tried writelines , i tried moving the with open()
method outside of my for loop but i seem to missing something else.
edit:
i made a edit or two because i had two scripts and i wasnt sure which i copied and pasted , this has the string2 variable from where i was comparing to another for loop, but no big deal still the same issue.

from itertools import permutations

string2 = 'derp'
list1 = []
for i in permutations(string2):
    new = ''.join(i)
    print(new)
with open('file1.txt','w') as f:
    f.writelines(new)
Maybe something like this:

#! /usr/bin/env python3

from itertools import permutations

string = 'poodle'

with open('test.txt', 'w') as file:
    for mutated in permutations(string):
        file.write(f'{"".join(mutated)}\n')
(Dec-05-2021, 09:13 PM)menator01 Wrote: [ -> ]Maybe something like this:

#! /usr/bin/env python3

from itertools import permutations

string = 'poodle'

with open('test.txt', 'w') as file:
    for mutated in permutations(string):
        file.write(f'{"".join(mutated)}\n')

Thanks , this works, I didn’t expect my old laptop to completely freeze while python ran through the permutations of my 11 letter name 😆
Also i just overlooked placing the for loop within the with open() method.
I think that I thought it wouldn’t work. I should have tried it at least.