如何在Python中一次性列出多目录下的文件路径
修正后的多目录MP4文件列表生成脚本
需求说明
处理1-10个动态传入的目录,遍历所有目录下的MP4文件,将路径格式化为file '完整路径'的形式写入单个file_list.txt文件,通过sys.argv[1:]自动获取所有传入的目录参数。
原脚本问题点
with open代码块内错误将文件句柄重新赋值为列表,导致后续write操作抛出属性错误- 错误使用
os.path.join拼接前缀与路径,破坏标准路径生成逻辑 - 默认使用追加模式
'a',多次运行易导致文件内容重复
修正后的Python脚本
import fnmatch import os import sys # 获取命令行传入的所有目录参数 target_dirs = sys.argv[1:] output_filename = 'file_list.txt' # 以写入模式打开文件(每次生成全新列表,需追加则改为'a') with open(output_filename, 'w', encoding='utf-8') as output_file: for dir_path in target_dirs: # 跳过不存在的目录,避免脚本崩溃 if not os.path.isdir(dir_path): print(f"Warning: Directory {dir_path} does not exist, skipped.") continue # 遍历目录下所有层级的文件 for root, _, filenames in os.walk(dir_path): # 筛选所有MP4格式文件 for mp4_file in fnmatch.filter(filenames, '*.mp4'): # 生成标准完整文件路径 full_file_path = os.path.join(root, mp4_file) # 按要求格式写入文件 output_file.write(f"file '{full_file_path}'\n")
批处理文件(可直接使用)
@echo off set dir_1=F:\VIDEO set dir_2=F:\Music python list.py %dir_1% %dir_2% pause
关键修正说明
- 保留
with open的文件句柄,避免覆盖导致的写入错误 - 先通过
os.path.join生成标准文件路径,再包裹指定格式的前缀后缀,确保路径合法性 - 添加目录存在性检查,提升脚本健壮性
- 指定
encoding='utf-8',兼容含中文或特殊字符的路径 - 默认使用
'w'模式生成新文件,如需保留历史记录可改为'a'模式
内容的提问来源于stack exchange,提问作者Ionut Bejinariu
相关产品推荐
相关产品推荐

