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)
相关推荐
神仙别闹17 分钟前
基于C语言开发的捕捉流星小游戏
c语言·开发语言
程序员Sunday30 分钟前
Promise.all、allSettled、race、any 怎么选,失败后其他请求会怎样
开发语言·前端·javascript
小静AI工程实验室1 小时前
Python 爬虫解析 JSON-LD:多块 script、@graph 与坏数据的 9 个边界
爬虫·python·json
daxiangxm1 小时前
GEO策略:让AI直接引用你的内容
开发语言·团队开发·运维开发·个人开发·数据库开发
jason.zeng@15022071 小时前
(八)现有架构上新增一个通用Excel导出工具
python·架构·langchain·excel·llama
袁袁袁袁满1 小时前
AI Agent 如何“看懂“互联网?
爬虫·python·自动化·爬虫实战·多线程爬虫
泡海椒1 小时前
JQuick-Excel 实战:用 VALIDATION 建立可维护的 Excel 导入校验
开发语言·python·excel
longlongzihan1 小时前
前缀积与后缀积 —— LeetCode 238. 除了自身以外数组的乘积
开发语言·c++·leetcode
Duang007_1 小时前
生产可观测性:从“系统慢“到“根因“的完整链路(Go / TypeScript)
后端·python·golang·typescript·prometheus
szial1 小时前
JavaScript 的 call、apply 和 bind:如何控制函数调用
开发语言·前端·javascript