生成200,000个哈希的列表并保存到文件

时间:2015-06-12 16:47:49

标签: python while-loop

我写了这个快速脚本来生成200,000个哈希随机值并将它们保存到文件中,但是当我运行文件时我收到了这个错误:" TypeError: expected a character buffer object"在线:file_.write(hash)

import random

hash = random.SystemRandom()
file_ = open('output.txt', 'w')

count = 0

while count < 200000:
    file_.write(hash)

file_.close()

我做错了什么?谢谢。

2 个答案:

答案 0 :(得分:3)

发现你做错了什么:

打开交互式shell,输入脚本的位:

>>> import random
>>>
>>> random.SystemRandom()
<random.SystemRandom object at 0x03FD83C8>

这不是数字,不是文字。您无法将其写入文件。

查看文档:

https://docs.python.org/2/library/random.html#random.SystemRandom

这是一个随机数生成器。您需要像random一样使用它。 random.random()random.randint(...)或其他内容。

然后在写入文件之前将其转换为str(...)的文本。

答案 1 :(得分:0)

您收到错误,因为哈希不是可以写入文件的类型。如果你想获得一定数量的随机性,并将其写入文件,你可以OpenWindow is not defined,虽然这会给你一个整数作为输出。此外,您的循环不会终止,因为您没有递增计数。我建议改用for循环。