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说来简单也简单,但是也不简单,尤其是再跟高数结合起来的时候。。。 正态分布(Normaldistribution),也称“常态分布”,又名高斯分布(Gaussiandistr...

Python  Django 母版和继承解析

Python Django 母版和继承解析

可以把多个页面相同的部分提取出来,放在一个母板里,这些页面只需要继承这个母板就好了 通常会在母板中定义页面专用的 CSS 块和 JS 块,方便子页面替换 定义块: {% block...

python检测某个变量是否有定义的方法

本文实例讲述了python检测某个变量是否有定义的方法。分享给大家供大家参考。具体如下: 第一种方法使用内置函数locals(): 'testvar'   in&nb...

解决django中ModelForm多表单组合的问题

解决django中ModelForm多表单组合的问题

django是python语言快速实现web服务的大杀器,其开发效率可以非常的高!但因为秉承了语言的灵活性,django框架又太灵活,以至于想实现任何功能都有种“条条大路通罗马”的感觉。...

flask中主动抛出异常及统一异常处理代码示例

flask中主动抛出异常及统一异常处理代码示例

本文主要介绍的是flask中主动抛出异常及统一异常处理的相关内容,具体如下。 在开发时,后台出现异常 ,但不想把异常显示给用户或者要统一处理异常时,可以使用abort主动抛出异常,再捕获...