0

I'm looking for a way to get the output that I'm printing out here written in a .txt file

for y in list(permutations(sllist, 3)):
        print("".join(y))

The Output in the console looks like that:

ccccaaaaaaaabbbbdddddddddd
ccccaaaaaaaabbbbeeeeeee
ccccaaaaaaaabbbbfff
ccccaaaaaaaabbbbgggggggggggg
ccccaaaaaaaabbbb2001
ccccaaaaaaaabbbb01
ccccaaaaaaaabbbb06

And that's exactly how I want to write it in the .txt file. Neatly arranged among each other. Thanks in advance.

Jakl
  • 23
  • 4
  • 1
    Please clarify the problem. Don't you know how to write to a file? The read ["Reading and Writing Files"](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files) in the tutorial. – Matthias Apr 01 '21 at 09:01

1 Answers1

2

Use a context manager to open the file, so that it will be automatically and correctly closed, even if the code inside raises exceptions.

As pointed out in the comments, there is no need to create the whole list in memory, you can iterate over the object returned by permutations and each element will be produced as needed.

from itertools import permutations

sllist = "abcd"

with open("output.txt", "w") as f:
    for y in permutations(sllist, 3):
        line = "".join(y)
        print(line)
        f.write(f"{line}\n")

Cheers!

Pietro
  • 1,090
  • 2
  • 9
  • 15
  • Possible optimization: Don't create a list from the return value of `permutations`. There's no need to hold the whole list in memory. `for y in permutations(sllist, 3):` should be enough. – Matthias Apr 01 '21 at 09:08
  • Of course, thank you, I've added it to the answer. – Pietro Apr 01 '21 at 09:14