Python 如何从多个子文件夹中随机选择文件

Python 如何从多个子文件夹中随机选择文件,python,python-3.6,Python,Python 3.6,我有多个子文件夹,每个子文件夹都有多个文件。我需要随机选择子文件夹,然后需要在该子文件夹中随机选择一个文件。假设我有五个文件夹A、B、C、D、E,每个文件夹包含另一个名为data的文件夹,这个data文件夹包含多个文件。我需要从五个文件夹中随机选择文件夹,然后打开数据文件夹,最后随机选择一个文件。将文件夹名称保留在列表中。 随机输入 导入操作系统 文件夹=[0,1,2,3,4] 所选文件夹=随机。选择(文件夹) 路径=所选文件夹+“/data” 现在要从路径中获取随机文件,请执行random

我有多个子文件夹,每个子文件夹都有多个文件。我需要随机选择子文件夹,然后需要在该子文件夹中随机选择一个文件。假设我有五个文件夹A、B、C、D、E,每个文件夹包含另一个名为data的文件夹,这个data文件夹包含多个文件。我需要从五个文件夹中随机选择文件夹,然后打开数据文件夹,最后随机选择一个文件。

将文件夹名称保留在列表中。

随机输入
导入操作系统
文件夹=[0,1,2,3,4]
所选文件夹=随机。选择(文件夹)
路径=所选文件夹+“/data”

现在要从路径中获取随机文件,请执行random.choice()并传递该路径中的文件列表。 使用os.listdir(path)获取文件列表。

尝试以下操作:(Python文件必须与这5个文件夹位于同一主文件夹中)

导入操作系统,随机
lst=list(过滤器(lambda x:os.path.isdir(x),os.listdir('.'))//获取文件夹列表
folder=random.choice(lst)//选择random文件夹
chdir(os.path.join(os.path.dirname(_文件,文件夹,'data'))//转到随机文件夹/data
lst=list(过滤器(lambda x:os.path.isfile(x),os.listdir('.'))//获取文件列表
file=random.choice(lst)//获取随机文件
打印(文件)

据我所知,构建代码块实际上需要4个函数:

  • os.listdir(path)
    它列出某个位置的所有文件和目录
  • os.path.isdir(path)
    检查位置中的元素是否为目录
  • os.path.isfile(path)
    idem与文件
  • random.randrange(X)
    查找范围[0;X]中的随机数[
我相信您可以很容易地找到关于这些函数的文档,因为它们都在python的标准库中

import os
import random

path = "/home/johndoe/"
dirs  = list(filter(lambda dir: os.path.isdir(os.path.join(path, dir)), os.listdir(path)))

dir_chosen = dirs[random.randrange(len(dirs))]

files_path = os.path.join(path, dir_chosen, "data")
files = list(filter(lambda file: os.path.isfile(os.path.join(files_path, file)), os.listdir(files_path)))

file_chosen = files[random.randrange(len(files))]

print("the file randomly chosen is: {}".format(os.path.join(files_path, file_chose )))

您还可以检查
os.path.join(a,b)
如果您不知道它,但它基本上相当于UNIX上的
a+/'+b
和Windows上的
a+'\'+b

到目前为止您做了哪些尝试?用于从列表中选择一个随机项。与其他回答问题的人一样,
随机。选择
random.randrange
更好。

import os
import random

path = os.getcwd()

def getRandomFile(path):
    randomDir = random.choice([(x) for x in list(os.scandir(path)) if x.is_dir()]).name
    randomFile = random.choice([f for f in list(os.scandir(randomDir + "\\data\\"))]).name
    return randomFile

print(getRandomFile(path))