Home  >  Article  >  Backend Development  >  重命名批处理python脚本

重命名批处理python脚本

WBOY
WBOYOriginal
2016-06-06 11:27:541157browse

将Copy of ********.bmp或者Copy of Copy of ********.bmp 此类文件统一命名为********0.bmp 或者********00.bmp等格式,后面的0的个数代表********.bmp出现的次数+1。写了个下面的小脚本:

代码如下:


import os
"""
这个程序是用来将文件名改名,因为在文件夹里面有很多Copy of 重文件名,因此去掉windows
重命名风格而换用新的累加命名机制
作者:chenxofHit@gmail.com
时间:2011年4月13日
"""
def getFileNames(dirs, dict):
#dir为目录名,lst列表
filenames=os.listdir(dirs)
for name in filenames:
key = filenames[filenames.index(name)]
sign = "Copy Of "
judge = key.find(sign)
if (judge != -1 ):
dict[key] = 1
else: #提取其中的真实文件名
trueKey= key[-12:] #因为真实的文件名都是在12位
if trueKey not in dict: #字典中不存在
dict[trueKey]=1
os.rename(dirs+str(os.sep)+name,dirs+str(os.sep)+trueKey)
else:
#split finames
newKey= str(trueKey[:-4])+str('0'*dict[trueKey])+ str(trueKey[-3:])
dict[trueKey] = dict[trueKey]+1
os.rename(dirs+os.sep+name,dirs+os.sep+newKey)

if '__name__=__main__':
dict={}
dirs = "C://temp"
getFileNames(dirs, dict)


用到了字典,用到了os模块,学到了一些东西,呵呵!
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn