【发布时间】:2021-04-29 16:59:20
【问题描述】:
所以我对 python 很陌生,每天学习一个新概念。我正在测试操作系统模块,我希望能够制作 1000 多个随机文件夹而不会重复。下面是我的代码,但缺陷是随机的。由于某种原因,示例给了我重复的数字。
还可以随意清理代码并以更简单的方式完成它,我很新,所以很想看到新事物。
import os
import random
#directory i want to make the folders in
os.chdir('C:\\Users\\miner2\\Desktop\\OS-Demo-2')
def newfl(foldername):
""" function that takes whatever you want to name the folder
and then adds a random number to the end of its name """
convert = random.sample(range(1,100000), 1)
return str(foldername) + ''.join((str(convert)))
#testing the function with print
print(newfl(1))
#attempting to make 10,000 folders by looping, but gives less because we get repeated folder names
i = 0
while i < 10000:
os.makedirs('C:\\Users\\miner2\\Desktop\\OS-Demo-2' + '\\' + str(newfl('putfoldernamehere')))
i += 1
【问题讨论】:
-
更新:这样做但我觉得它很脏 convert = random.sample(range(1,200), 15) return str(foldername) + ''.join((str(convert)) )
-
您似乎已经知道如何随机抽样 - 为什么不抽样 10000 个不同的值一次,而不是抽样 1 个独立值 10000 次?