如何让Python按创建/修改日期枚举并重命名目录下文件?
按文件日期排序并重命名的解决方案
你遇到的问题核心是:sorted(os.listdir())仅按文件名排序,而非文件的创建/修改时间。要实现按日期排序后批量重命名,需要基于文件的时间属性自定义排序规则,以下是两种可行方案:
方案1:按文件修改时间排序
修改代码,先获取每个文件的最后修改时间,以此为依据排序后再枚举重命名:
import os # 目标目录路径 target_dir = r'/Users/al/Library/Mobile Documents/com~apple~CloudDocs/data/mental/tumor/2017' os.chdir(target_dir) print(os.getcwd()) # 按文件修改时间升序排序(旧文件在前,新文件在后) files = sorted(os.listdir(), key=lambda f: os.path.getmtime(f)) for count, f in enumerate(files): f_name, f_ext = os.path.splitext(f) new_name = f'tumor{count}{f_ext}' os.rename(f, new_name)
方案2:按文件创建时间排序(区分系统)
如果需要严格按创建时间排序,需根据操作系统调整:
- macOS/BSD系统:使用
os.stat(f).st_birthtime获取创建时间戳 - Windows系统:直接用
os.path.getctime(f)获取创建时间戳
macOS适配代码示例:
import os target_dir = r'/Users/al/Library/Mobile Documents/com~apple~CloudDocs/data/mental/tumor/2017' os.chdir(target_dir) print(os.getcwd()) # 按创建时间升序排序 files = sorted(os.listdir(), key=lambda f: os.stat(f).st_birthtime) for count, f in enumerate(files): f_name, f_ext = os.path.splitext(f) new_name = f'tumor{count}{f_ext}' os.rename(f, new_name)
额外调整说明
- 若需要降序排序(新文件在前),只需在
sorted()中添加reverse=True参数,例如:files = sorted(os.listdir(), key=lambda f: os.path.getmtime(f), reverse=True) - 批量处理多文件夹时,可将目录路径改为遍历列表,循环执行上述逻辑即可。
内容的提问来源于stack exchange,提问作者Alex Günsberg
相关产品推荐
相关产品推荐

