Python实现目录文件自然排序 解决超100个文件时计数错误问题
解决方案
你遇到的计数错误本质是默认目录遍历采用字典序排序(会出现10.html排在2.html前面的问题),你已经找到了正确的自然排序逻辑,只需在遍历前先对目录列表做排序即可,修改步骤如下:
- 确保代码开头已导入
os模块,排序逻辑依赖该模块的路径分割方法 - 遍历前先对目录列表执行排序,替换原有未排序的
iterable_directory - 建议提前过滤掉
index.html和非HTML文件,避免无效文件占用索引位导致上下文件判断出错
修改后的完整代码如下:
import os # 先执行排序+过滤,得到符合自然升序的目标文件列表 sorted_files = sorted( iterable_directory, key=lambda x: int(x.split(os.path.sep)[-1].split('-')[0]) if x != "index.html" else 0 ) # 过滤掉index.html和非HTML文件,得到纯目标文件列表 target_files = [f for f in sorted_files if f.endswith(".html") and not f.startswith("index")] file_count = len(target_files) for index, file in enumerate(target_files): print(f'At file {index+1} in the directory:\n') # 只有1个文件的情况 if file_count == 1: prev_video = '#' next_video = '#' # 第一个文件 elif index == 0: prev_video = '#' next_video = target_files[index+1] # 最后一个文件 elif index == file_count - 1: prev_video = target_files[index-1] next_video = '#' # 中间文件 else: prev_video = target_files[index-1] next_video = target_files[index+1] print(f'The prev vid is {prev_video}\nThe next vid is {next_video}\n')
关键修改说明
- 所有文件遍历操作都基于排序后的
target_files列表,完全符合你要的序号升序规则 - 提前过滤无效文件后不需要再做重复的后缀和文件名判断,索引计算更准确,避免了原代码中取
[-2]、[-3]的偏移错误问题 - 兼容任意数量的文件场景,不会出现超过100个文件就排序混乱的问题
内容的提问来源于stack exchange,提问作者Nahuel Mel
相关产品推荐
相关产品推荐

