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 enumerate函数遍历数据对象组合过程解析

这篇文章主要介绍了Python enumerate函数遍历数据对象组合过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 介绍...

Python编写的com组件发生R6034错误的原因与解决办法

解决该问题的方法可以为调用本程序的exe文件建立一个合适的manifest文件,指定正确的msvcr90.dll版本即可,具体可参照/post/35219.htm ps:可以使用mt.e...

Python cookbook(数据结构与算法)字典相关计算问题示例

本文实例讲述了Python cookbook(数据结构与算法)字典相关计算问题。分享给大家供大家参考,具体如下: 问题:在字典上对数据执行各式各样的计算(比如求最小值、最大值、排序)。...

python得到一个excel的全部sheet标签值方法

这里需要用到python处理excel很经典的库openpyxl,安装也特别简单。window直接pip install就好了 代码在这里~ wb = openpyxl.load_w...

详解Python的Django框架中manage命令的使用与扩展

【简介】 django-admin.py是Django的一个用于管理任务的命令行工具。本文将描述它的大概用法。 另外,在每一个Django project中都会有一个manage.py。...