生成随机10位文件名并创建fi的代码

2024-10-01 04:54:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用:

import random
filenamemaker = random.randint(1,1000)

所有的帮助都很好谢谢:)


Tags: importrandomrandintfilenamemaker
3条回答

最简单的方法是使用^{}和{a2}。如果不打算使用文件并自动关闭文件,也可以使用^{}语句,其中包含一个空的^{}

from string import digits
from random import sample 

with open("".join(sample(digits, 10)), 'w'): 
    pass

这相当于:

^{pr2}$

对于连续调用,这将生成文件名,例如:

3672945108  6298517034

randint有两个参数:生成的数字的下限和上限。您的代码将生成一个介于1到1000之间的数字(包括1到4位数)。在

这将生成一个介于1和999999999之间的数字:

>>> n = random.randint(1, 9999999999)

如果少于10位,则需要用零填充并将其设为字符串:

^{pr2}$

然后您可以打开并写入:

with open(filename + '.txt', 'w') as f:
    # do stuff
    pass
import random

filename = ""
for i in range(10):
    filename += str(random.randint(0,9))

f = open(filename + ".txt", "w")

相关问题 更多 >