最近的工作中遇到了这样的问题:某一批文件以"XXX_1.xxx","XXX_2.xxx"..."XXX_11.xxx","XXX_12.xxx"...命名,在我的电脑上它是以数字从小到大的方式排序的,但在另一台设备上则是以字典序排序的,即"XXX_1.xxx","XXX_11.xxx","XXX_12.xxx"..."XXX_2.xxx","XXX_21.xxx"...,为了解决这个问题,我尝试为这些文件的序号添加前缀0,改为"XXX_001.xxx","XXX_002.xxx"..."XXX_011.xxx","XXX_012.xxx"...的形式.
实现的方法是遍历所有文件,将文件名排序,然后逐个改名即可.
# -*- coding: UTF-8 -*- import os from functools import cmp_to_key def digit_id(s): #返回字符串尾部的数字是从第几位开始的 for i in range(-1,-len(s)-1,-1): if(not s[i].isdigit()): return i+1 return -len(s) def cmp(t1,t2): #自定义比较函数 filename1=t1.split('.',1)[0] num1=filename1[digit_id(filename1):] filename2=t2.split('.',1)[0] num2=filename2[digit_id(filename2):] return int(num1)-int(num2) workpath='./' filenames=filter(lambda x:x[-4:]=='.jpg', os.listdir(workpath)) #只读取jpg类型的文件 filenames=sorted(filenames,key=cmp_to_key(cmp)) print(filenames) l=-digit_id(filenames[-1].split('.',1)[0]) #找出位数最大的那个文件是多少位 for i in range(len(filenames)): #开始重命名 oldname=filenames[i].split('.',1) d=digit_id(oldname[0]) newname=oldname[0][:d]+('0'*(l+d))+oldname[0][d:]+'.'+oldname[1] os.rename(os.path.join(workpath,filenames[i]),os.path.join(workpath,newname))
标签:重命名,...,digit,XXX,Python,xxx,filenames,oldname,文件批量 From: https://www.cnblogs.com/isakovsky/p/17265853.html