python 批量重命名-格式化与排序

背景

上一次给客户重新命名后,客户再制作开机动画bootanimation的时候又提出新要求
本着客户永远是对的原则,按需进行调试
客户的文件以数字命名 有排序的趋势但不是严格的等差数列
要求按照现有顺序排列 然后进行重命名 从0001开始 固定文件名为4位

技术细节

  • 文件排序
  • 新文件名的格式化输出

分析

  • 文件排序
    基于现状 需要去掉文件后缀 ,将文件字符按照其数字大小排序
    sort函数中使用匿名函数(key = lambda x:int(x[:-4]))来过滤掉后缀
    保证输出结果的顺序
  • 格式化输出
    新文件基于int数字 使用了python的格式化输出表达
    举个例子
  n = 123
  s = "%04d" % n
  assert s == "0123"

Demo

# -*- coding: utf-8 -*-
"""
@author: dingguagua
"""
import os
import re
path = r'720x1560bootanimation\part0 改'

# 将一些文件按顺序重命名
def rename_sort():
    img_list = os.listdir(path)
    img_list.sort(key=lambda x: int(x[:-4]))
    i =1
    for file in img_list:
        print(file)
        print("new:","%04d" %i+file[-4:])
        os.rename(os.path.join(path, file), os.path.join(path, "%04d" %i+file[-4:]))
        i =i+1


if __name__ == '__main__':
    #rename_filter()
    rename_sort()

总结

利用python可以提高bootanimation制作效率 减少美工人员的劳动量 讲精力用于创造

posted on 2021-09-23 18:56  小王的一天  阅读(340)  评论(0)    收藏  举报

导航