Python递归遍历子目录并生成多级m3u8文件的技术实现需求
Python Solution for Recursive File Listing & Directory-specific M3U8 Generation
Alright, let's build a Python solution that checks both of your boxes. We'll use pathlib (Python 3.4+) for clean, object-oriented file system handling, which makes recursive traversal and path manipulation a breeze.
Full Code Implementation
import pathlib def write_all_files_to_output(root_dir: str, output_file_path: str): """递归遍历指定根目录下的所有文件,将完整路径写入输出文件""" root_path = pathlib.Path(root_dir) # 递归收集所有文件的完整路径(排除目录) all_files = [str(file.resolve()) for file in root_path.rglob("*") if file.is_file()] # 写入输出文件,使用UTF-8编码避免中文/特殊字符乱码 with open(output_file_path, 'w', encoding='utf-8') as output_file: output_file.write('\n'.join(all_files)) print(f"Successfully wrote all files to {output_file_path}") def create_directory_m3u8s(root_dir: str): """为每个子目录(包括根目录)生成同名M3U8文件,包含该目录下所有递归文件的相对路径""" root_path = pathlib.Path(root_dir) # 遍历根目录下的所有目录(含自身) for dir_path in root_path.rglob("*"): if dir_path.is_dir(): # 构建M3U8文件路径:当前目录下的[目录名].m3u8 m3u8_file_path = dir_path / f"{dir_path.name}.m3u8" # 收集当前目录下所有递归文件的相对路径(相对于当前目录) relative_file_paths = [] for file in dir_path.rglob("*"): if file.is_file(): rel_path = file.relative_to(dir_path) relative_file_paths.append(str(rel_path)) # 写入M3U8文件,添加标准M3U8头部 with open(m3u8_file_path, 'w', encoding='utf-8') as m3u8_file: m3u8_file.write("#EXTM3U\n") # M3U8标准头部,可按需移除 for rel_path in relative_file_paths: m3u8_file.write(f"{rel_path}\n") print(f"Generated {m3u8_file_path}") if __name__ == "__main__": # 替换为你的目标根目录路径 TARGET_ROOT = "/path/to/your/Music" # 替换为你的输出文件路径(用于存储所有文件列表) OUTPUT_FILE = "/path/to/your/all_files_list.txt" # 执行第一个功能:导出所有文件到输出文件 write_all_files_to_output(TARGET_ROOT, OUTPUT_FILE) # 执行第二个功能:为每个目录生成M3U8 create_directory_m3u8s(TARGET_ROOT)
Key Details & Explanations
write_all_files_to_output:
- Uses
pathlib.Path.rglob("*")to recursively match all items in the root directory, then filters for files only. - Writes full resolved paths (absolute paths) to the output file, ensuring you can directly access any file from the list.
- Uses UTF-8 encoding to handle non-ASCII filenames (like Chinese or special characters) without errors.
- Uses
create_directory_m3u8s:
- Traverses every directory (including the root) under your target path.
- Generates an M3U8 file named after the directory, placed directly inside that directory.
- Stores relative paths for each file (relative to the directory containing the M3U8), which ensures the playlist works even if you move the directory elsewhere.
- Includes the
#EXTM3Uheader, which is the standard start for M3U8 playlists (you can remove this line if you don't need it).
Notes
- Make sure you have read/write permissions for the target root directory and all its subdirectories.
- If you're dealing with an extremely large number of files, this solution is efficient enough, but you could add progress tracking if needed.
- To test, replace
TARGET_ROOTandOUTPUT_FILEwith your actual paths before running the script.
内容的提问来源于stack exchange,提问作者bayman
相关产品推荐
相关产品推荐

