重命名批处理python脚本

yipeiwu_com6年前Python基础

将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模块,学到了一些东西,呵呵!                                                

相关文章

PYTHON压平嵌套列表的简单实现

list 是 Python 中使用最频繁的数据类型, 标准库里面有丰富的函数可以使用。 不过,如果把多维列表转换成一维列表(不知道这种需求多不多),还真不容易找到好用的函数, 要知道...

在python 中实现运行多条shell命令

使用py时可能需要连续运行多条shell 命令 1. # coding: UTF-8 import sys reload(sys) sys.setdefaultencoding('u...

python程序快速缩进多行代码方法总结

python程序快速缩进多行代码方法总结

该语言中缩进是其精髓,通过缩进可以表示函数、循环等程序结构的范围。有时写完程序后,发现所有程序需要放入函数def中,这时就需要对一整块程序同时进行缩进,还有其他一些情况,也会需要多行整体...

使用Python脚本来获取Cisco设备信息的示例

今天发现一个使用python写的管理cisco设备的小框架tratto,可以用来批量执行命令。 下载后主要有3个文件: Systems.py 定义了一些不同设备的操作系统及其常见命令。...

Python编程scoketServer实现多线程同步实例代码

本文研究的主要是Python编程scoketServer实现多线程同步的相关内容,具体介绍如下。 开发过程中,为了实现不同的客户端同一时刻只能有一个使用共同数据。 虽说用Python编写...