从目录中选择随机文件的最佳方法 [英] Best way to choose a random file from a directory

查看:81
本文介绍了从目录中选择随机文件的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从Python目录中选择随机文件的最佳方法是什么?

What is the best way to choose a random file from a directory in Python?

这是我在做什么:

import os
import random
import dircache

dir = 'some/directory'
filename = random.choice(dircache.listdir(dir))
path = os.path.join(dir, filename)

这是不是特别糟糕,还是有一种更好的方法?

Is this particularly bad, or is there a particularly better way?

推荐答案

import os, random
random.choice(os.listdir("C:\\")) #change dir name to whatever


关于您编辑过的问题:首先,我假设您知道使用dircache的风险,以及它是


Regarding your edited question: first, I assume you know the risks of using a dircache, as well as the fact that it is deprecated since 2.6, and removed in 3.0.

第二,我看不出这里存在任何比赛条件.您的dircache对象基本上是不可变的(在缓存目录列表之后,再也不会读取它了),因此从它的并发读取中不会造成任何损害.

Second of all, I don't see where any race condition exists here. Your dircache object is basically immutable (after directory listing is cached, it is never read again), so no harm in concurrent reads from it.

除此之外,我不明白为什么您会看到此解决方案有任何问题.很好.

Other than that, I do not understand why you see any problem with this solution. It is fine.

这篇关于从目录中选择随机文件的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆