【问题标题】:Trying to make 1000 random folders using Python - os.makedirs()尝试使用 Python 创建 1000 个随机文件夹 - os.makedirs()
【发布时间】: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 次?

标签: python operating-system


【解决方案1】:

random.sample() 样本没有替换,但函数调用之间不保留唯一性。

另外,pathlibos 模块的不错替代品。

这应该可行:

import pathlib
import random

base_path = pathlib.Path("C:/Users/miner2/Desktop/OS-Demo-2")

for i in random.sample(range(10000), k=500)):
    base_path.joinpath(f"folder_{i}").mkdir()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-26
    • 2013-12-09
    • 1970-01-01
    • 2017-09-13
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多