从目录中选择随机文件的最佳方法

Jas*_*ith 31 python random file

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

编辑:这是我正在做的事情:

import os
import random
import dircache

dir = 'some/directory'
filename = random.choice(dircache.listdir(dir))
path = os.path.join(dir, filename)
Run Code Online (Sandbox Code Playgroud)

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

Yuv*_*dam 63

import os, random
random.choice(os.listdir("C:\\")) #change dir name to whatever
Run Code Online (Sandbox Code Playgroud)

关于您编辑过的问题:首先,我假设您了解使用a的风险dircache,以及自2.6以来弃用并在3.0中删除的事实.

其次,我不知道这里存在任何竞争条件.您的dircache对象基本上是不可变的(在缓存目录列表之后,它永远不会被再次读取),因此并发读取不会造成任何损害.

除此之外,我不明白为什么你看到这个解决方案有任何问题.没事.


mav*_*vnn 7

如果你想要包含目录,Yuval A的回答.除此以外:

import os, random

random.choice([x for x in os.listdir("C:\\") if os.path.isfile(os.path.join("C:\\", x))])
Run Code Online (Sandbox Code Playgroud)


kei*_*ley 7

给出的大多数解决方案的问题是您将所有输入加载到内存中,这可能成为大型输入/层次结构的问题。这是改编自Tom Christiansen 和 Nat Torkington 的The Perl Cookbook的解决方案。要在目录下的任何位置获取随机文件:

#! /usr/bin/env python
import os, random
n=0
random.seed();
for root, dirs, files in os.walk('/tmp/foo'):
  for name in files:
    n += 1
    if random.uniform(0, n) < 1:
        rfile=os.path.join(root, name)
print rfile
Run Code Online (Sandbox Code Playgroud)

概括一点可以制作一个方便的脚本:

$ cat /tmp/randy.py
#! /usr/bin/env python
import sys, random
random.seed()
n = 1
for line in sys.stdin:
  if random.uniform(0, n) < 1:
      rline=line
  n += 1
sys.stdout.write(rline)

$ /tmp/randy.py < /usr/share/dict/words 
chrysochlore

$ find /tmp/foo -type f | /tmp/randy.py
/tmp/foo/bar
Run Code Online (Sandbox Code Playgroud)


THE*_*TDW 6

最简单的解决方案是使用os.listdirrandom.choice方法

random_file=random.choice(os.listdir("Folder_Destination"))
Run Code Online (Sandbox Code Playgroud)

让我们一步一步来看看它:-

1} os.listdir方法返回包含指定路径中条目(文件)名称的列表。

2} 然后将此列表作为参数传递给random.choice方法,该方法从列表中返回随机文件名。

3} 文件名存储在random_file变量中。


考虑实时应用

这是一个示例 python 代码,它将随机文件从一个目录移动到另一个目录

import os, random, shutil

#Prompting user to enter number of files to select randomly along with directory
source=input("Enter the Source Directory : ")
dest=input("Enter the Destination Directory : ")
no_of_files=int(input("Enter The Number of Files To Select : "))

print("%"*25+"{ Details Of Transfer }"+"%"*25)
print("\n\nList of Files Moved to %s :-"%(dest))

#Using for loop to randomly choose multiple files
for i in range(no_of_files):
    #Variable random_file stores the name of the random file chosen
    random_file=random.choice(os.listdir(source))
    print("%d} %s"%(i+1,random_file))
    source_file="%s\%s"%(source,random_file)
    dest_file=dest
    #"shutil.move" function moves file from one directory to another
    shutil.move(source_file,dest_file)

print("\n\n"+"$"*33+"[ Files Moved Successfully ]"+"$"*33)
Run Code Online (Sandbox Code Playgroud)

您可以在 github Random File Picker查看整个项目


有关os.listdirrandom.choice方法的附加参考,您可以参考教程点学习 python

os.listdir :- Python listdir() 方法

random.choice :- Python choice() 方法



kar*_*m79 5

与语言无关的解决方案:

1)获取总数量 指定目录中的文件。

2) 从 0 到 [总数] 中选择一个随机数。文件数 - 1]。

3) 获取文件名列表作为适当索引的集合等。

4)选取第n个元素,其中n是随机数。