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)
相关推荐
小陈工2 小时前
Python Web开发入门(十七):Vue.js与Python后端集成——让前后端真正“握手言和“
开发语言·前端·javascript·数据库·vue.js·人工智能·python
H Journey2 小时前
C++之 CMake、CMakeLists.txt、Makefile
开发语言·c++·makefile·cmake
A__tao6 小时前
Elasticsearch Mapping 一键生成 Java 实体类(支持嵌套 + 自动过滤注释)
java·python·elasticsearch
研究点啥好呢6 小时前
Github热门项目推荐 | 创建你的像素风格!
c++·python·node.js·github·开源软件
lly2024066 小时前
C 标准库 - `<stdio.h>`
开发语言
沫璃染墨6 小时前
C++ string 从入门到精通:构造、迭代器、容量接口全解析
c语言·开发语言·c++
jwn9996 小时前
Laravel6.x核心特性全解析
开发语言·php·laravel
迷藏4946 小时前
**发散创新:基于Rust实现的开源合规权限管理框架设计与实践**在现代软件架构中,**权限控制(RBAC)** 已成为保障
java·开发语言·python·rust·开源
功德+n7 小时前
Linux下安装与配置Docker完整详细步骤
linux·运维·服务器·开发语言·docker·centos
明日清晨7 小时前
python扫码登录dy
开发语言·python