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)
相关推荐
合作小小程序员小小店10 分钟前
桌面安全开发,桌面二进制%恶意行为拦截查杀%系统安全开发3.0,基于c/c++语言,mfc,win32,ring3,dll,hook,inject,无数据库
c语言·开发语言·c++·安全·系统安全
合作小小程序员小小店10 分钟前
桌面开发,超市管理系统开发,基于C#,winform,sql server数据库
开发语言·数据库·sql·microsoft·sqlserver·c#
Codeking__12 分钟前
C++ 11 atomic 原子性操作
开发语言·c++
懂得节能嘛.19 分钟前
【Java动态线程池】Redis监控+动态调参
java·开发语言·redis
ModestCoder_1 小时前
ROS Bag与导航数据集技术指南
开发语言·人工智能·自然语言处理·机器人·具身智能
卡提西亚1 小时前
C++笔记-34-map/multimap容器
开发语言·c++·笔记
2***B4491 小时前
C++在金融中的QuantLibXL
开发语言·c++·金融
A***07171 小时前
C++在游戏中的阴影渲染
开发语言·c++·游戏
2401_837088501 小时前
Redisson的multilock原理
java·开发语言