最简单的解决方案是使用 os.listdir 和 random.choice 方法
random_file=random.choice(os.listdir("Folder_Destination"))
让我们一步一步来看看吧:-
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)
你可以在 github 上查看整个项目
Random File Picker
os.listdir和random.choice方法的补充参考可以参考tutorialspoint learn python
os.listdir :- Python listdir() method
random.choice :- Python choice() method