【问题标题】:Is there any way to write this type of permutations in a text file line by line?有没有办法在文本文件中逐行写入这种类型的排列?
【发布时间】:2019-12-29 11:42:12
【问题描述】:

我有这个代码:

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()

但它不起作用。当我运行 .py 文件时 Output.txt 已创建,但当我打开它时,我看到一个向上箭头。我想看到这样的输出:

1
2
3
4
...

【问题讨论】:

  • 为什么每次迭代都打开和关闭文件?这将每次覆盖文件。只需在循环之前/之后打开和关闭一次,甚至更好,使用with
  • @DeepSpace 我不熟悉python。你能解释一下吗?
  • 1 作为r 的值传递给itertools.permutations 只会返回一个列表,其中包含string.printable 中每个字符的元组,这似乎不是很有用?你也可以直接遍历string.printable
  • @Iain Shelvington 这只是一个例子。我真的不希望 1 作为 r 的值。

标签: python python-3.x permutation


【解决方案1】:

您在每次迭代中都使用w 模式打开和关闭文件,这意味着文件在每次迭代时都会被截断,这反过来意味着它始终只包含您写给它的最后内容。

您可以使用 a附加到文件的a 模式。

更好的方法是在循环之前打开文件一次,在循环之后关闭它一次。

最佳做法是使用with 上下文管理器(谷歌该术语以查找更多信息),它将为您处理文件的打开和关闭。

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)))

请注意,我在每行末尾添加了\n,因为我假设您希望每个排列都在单独的行中。

【讨论】:

  • 有什么办法可以把每个字符写成一行?
  • @ParsaFathollahi 是的,请参阅添加了 \n 的编辑答案
【解决方案2】:

另一种方式:

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

text_file = open("Output.txt", "w")
for v in variations:
    text_file.write(f"{v[0]}\n")

text_file.close()

如上所述,有更好的方法可以做到这一点。您每次迭代都打开文件,只打开一次。 v 是一个元组 ('1',) 等,所以你需要索引第一个元素。

【讨论】:

    猜你喜欢
    • 2019-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多