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.

1
  • 1
    Please clarify the problem. Don't you know how to write to a file? The read "Reading and Writing Files" in the tutorial. Commented Apr 1, 2021 at 9:01

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Of course, thank you, I've added it to the answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.