【发布时间】:2016-09-30 21:45:22
【问题描述】:
我尝试使用:
import random
filenamemaker = random.randint(1,1000)
所有的帮助都会非常感谢:)
【问题讨论】:
标签: python python-3.x random
我尝试使用:
import random
filenamemaker = random.randint(1,1000)
所有的帮助都会非常感谢:)
【问题讨论】:
标签: python python-3.x random
最简单的方法是使用string.digits 和random.sample。如果不打算使用该文件并自动希望它关闭,您也可以使用带有空 pass 的 with 语句:
from string import digits
from random import sample
with open("".join(sample(digits, 10)), 'w'):
pass
这相当于:
filename = "".join(sample(digits, 10))
f = open(filename, 'w')
f.close()
在连续调用时,这会生成如下文件名:
3672945108 6298517034
【讨论】:
import random
filename = ""
for i in range(10):
filename += str(random.randint(0,9))
f = open(filename + ".txt", "w")
【讨论】:
randint 接受两个参数:生成数字的下限和上限(包括)。您的代码将生成一个介于 1 到 1000(含)之间的数字,可以是 1 到 4 位之间的任何数字。
这将生成一个介于 1 和 9999999999 之间的数字:
>>> n = random.randint(1, 9999999999)
然后你需要用零填充它并使其成为一个字符串,以防它小于 10 位:
>>> filename = str(n).zfill(10)
然后您可以打开它并写入它:
with open(filename + '.txt', 'w') as f:
# do stuff
pass
【讨论】: