Python 文件重命名工具代码

yipeiwu_com5年前Python基础
复制代码 代码如下:

#Filename:brn.py
#Description: batch replace certain words in file names
#Use to bat rename the file in a dir(modify the suffix from a to b) for Windows Vista OS
import sys
import os
import fnmatch
import re
#parse params
p=input("Please input work directory(current path for enter):")
if p=='\r':
p='.'
p=p.rstrip('\r')
print (p)
while not os.path.exists(p):
print (p+' is not existed.Please input the work directory:')
p=input("Please input work directory(current path for enter):")
s=input("Please enter the words which need be modified(must):")
while s=='\r':
s=input("Please enter the words which need be replaced(must):")
s=s.rstrip('\r')
d=input("Please enter the words which want to change to(must):")
while d=='\r':
d=input("Please enter the words which want to change to(must):")
d=d.rstrip('\r')
try:
sure=input("Are you sure to rename the file named *"+s+"*"+" to *"+d+"*"+" in directory "+p+"? y/n:")
sure=sure.rstrip('\r')
if sure!='y':
print ("Cancel")
else:
for root, dirs, files in os.walk(p, True):
for file in files:
print (os.path.join(root,file))
if os.path.isfile(os.path.join(root,file)):#Only file is file,not a dir ,do this
if fnmatch.fnmatch(file, '*'+s+'*'):
f=str(file).replace(s,d)
if p=='.':
command='move '+str(file)+" "+f
else:
command="move "+os.path.join(root,file)+" "+os.path.join(root,f)
print (command)
if os.system(command)==0:#do actual rename
print ("Rename "+str(file)+" to "+f+" success")
else:
print ("Rename "+str(file)+" to "+f+" failed")
#else:
#print str(file)+" is a directory.omit"
except IndexError:
print (IndexError.message)

相关文章

python八大排序算法速度实例对比

python八大排序算法速度实例对比

这篇文章并不是介绍排序算法原理的,纯粹是想比较一下各种排序算法在真实场景下的运行速度。 算法由 Python 实现,可能会和其他语言有些区别,仅当参考就好。 测试的数据是自动生成的,以数...

在Linux下调试Python代码的各种方法

 这是一个我用于调试或分析工具概述,不一定是完整全面,如果你知道更好的工具,请在评论处标记。 日志 是的,的确,不得不强调足够的日志记录对应用程序是多么的重要。您应该记录重要的...

Selenium+Python 自动化操控登录界面实例(有简单验证码图片校验)

Selenium+Python 自动化操控登录界面实例(有简单验证码图片校验)

从最简单的Web浏览器的登录界面开始,登录界面如下: 进行Web页面自动化测试,对页面上的元素进行定位和操作是核心。而操作又是以定位为前提的,因此,对页面元素的定位是进行自动化测试的基...

Python处理CSV与List的转换方法

1.读取CSV文件到List def readCSV2List(filePath): try: file=open(filePath,'r',encoding="gbk")#...

Python面向对象之反射/自省机制实例分析

本文实例讲述了Python面向对象之反射/自省机制。分享给大家供大家参考,具体如下: 反射:程序可以访问,检测和修改它本身状态或行为的一种能力(自省) 下面就介绍四种实现自省的函数,适用...