要根据不同的需求随机选择目录下的文件路径,以下是两种常见情况的解决方案:
情况一:仅当前目录下的文件(不包含子目录)
# -*- coding: utf-8 -*-
# @Author : 小红牛
# 微信公众号:WdPython
import os
import random
def get_random_file_current_dir(dir_path):
# 获取当前目录下的所有文件(不包括子目录)
files = [os.path.join(dir_path, f) for f in os.listdir(dir_path)
if os.path.isfile(os.path.join(dir_path, f))]
if not files:
return None
return random.choice(files)
# 使用示例
directory = "D:/Wdpython/项目/"
selected_file = get_random_file_current_dir(directory)
print(selected_file if selected_file else "No files found in current directory.")
情况二:包含所有子目录中的文件
import os
import random
def get_random_file_recursive(dir_path):
# 递归遍历所有子目录,收集文件路径
file_list = []
for root, _, files in os.walk(dir_path):
for file in files:
file_path = os.path.join(root, file)
if os.path.isfile(file_path): # 再次确保是文件
file_list.append(file_path)
if not file_list:
return None
return random.choice(file_list)
# 使用示例
directory = "D:/Wdpython/项目/"
selected_file = get_random_file_recursive(directory)
print(selected_file if selected_file else "No files found in directory tree.")
核心区别
情况一:仅检查指定目录的直接子文件,速度快但范围有限。
情况二:递归遍历所有子目录,覆盖面广但可能耗时较长。
注意事项
路径需替换为实际存在的目录。
确保程序对目标目录有读取权限。
空目录会返回None,建议做好异常处理。
根据您的具体需求选择对应的方案即可。如果目录结构复杂推荐使用递归方案,若只需处理表层文件则用非递归方案更高效。
完毕!!感谢您的收看
----------★★跳转到历史博文集合★★----------
我的零基础Python教程,Python入门篇 进阶篇 视频教程 Py安装py项目 Python模块 Python爬虫 Json Xpath 正则表达式 Selenium Etree CssGui程序开发 Tkinter Pyqt5 列表元组字典数据可视化 matplotlib 词云图 Pyecharts 海龟画图 Pandas Bug处理 电脑小知识office自动化办公 编程工具 NumPy Pygame