python 遍历从重命名文件夹下的所有文件

收到一个文件包,里面的文件命名是1.png、2.png......但在手机上打开时,是按1/10/11/12这样排序的,不是按数字从小到大。因此,需要将所有的文件重命名为001.png这种带0前缀的格式。

python 复制代码
import os
import re

def traverse_rename(path):
    for root, dirs, files in os.walk(path):
        print(f'当前目录:{root}')
        # 处理文件
        print(f'文件数量{len(files)}')
        for file in files:
            # print(os.path.join(root, file))
            r = re.match(r'[0-9]+', file)
            if r:
                fill_0 = 3-r.span()[1]
                if fill_0 <= 0:
                    continue
                new_file = '0'*fill_0+file
                print(f'src:{file},dst:{new_file}')
                os.rename(os.path.join(root,file), os.path.join(root,new_file))


if __name__ == '__main__':
    path = r'D:\测试'
    traverse_rename(path)
相关推荐
databook13 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室14 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三15 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户25191624271119 小时前
Python之语言特点
python
刘立军19 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机1 天前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机1 天前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i1 天前
django中的FBV 和 CBV
python·django
c8i1 天前
python中的闭包和装饰器
python
这里有鱼汤1 天前
小白必看:QMT里的miniQMT入门教程
后端·python