首页 > 解决方案 > Is there any way to write this type of permutations in a text file line by line?

问题描述

I have this code:

import itertools
import string
variations = itertools.permutations(string.printable, 1)
for v in variations:
    text_file = open("Output.txt", "w")
    text_file.write(''.join(v))
    text_file.close()

But it doesn't work.When I run the .py file Output.txt is created but when I open it, I see an up arrow.I want to see an output like this:

1
2
3
4
...

标签: pythonpython-3.xpermutation

解决方案


You are opening and closing the file in every iteration with the w mode, which means the file gets truncated every iteration, which in turn means it will always contain only the last thing you wrote to it.

You may use the a mode which appends to the file.

A better approach will be to to open the file once before the loop, and close it once after the loop.

The best practice is to use the with context manager (google the term to find more info) which will handle the opening and closing of the file for you.

import itertools
import string

variations = itertools.permutations(string.printable, 1)

with open("Output.txt", "w") as f:
    for v in variations:
        f.write('{}\n'.format(''.join(v)))

Note that I added \n in the end of each line since I assumed you want each permutation in a separate line.


推荐阅读