python - 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
...
解决方案
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.
推荐阅读
- reactjs - react-virtualized中道具更改时如何滚动到底部?
- android - 具有引用另一个 ID 的可见性的数据绑定
- json - 无法在 jira 中发布 .json 文件
- postgresql - Postgres 服务未启动
- .net - MVC @HTML.ActionLink
- java - 通过 Jenkins 参数化 JUnit CucumberOptions
- json - 使用 Swift 解码器从 JSON 数组中提取属性
- node.js - 使用 sinon fake 进行单元测试无法解决承诺
- pytorch - 如何使用 Pytorch 将 FloatTensor 转换为 ByteTensor?
- ansible - ansible vmware windows 服务器