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验证码识别的实例详解

其实关于验证码识别涉及很多方面的内容,入手难度大,但是入手后,可拓展性又非常广泛,可玩性极强,成就感也很足,对这感兴趣的朋友们下面跟着小编一起来学习学习吧。 依赖 sudo apt-...

Python使用pyautocad+openpyxl处理cad文件示例

本文实例讲述了Python使用pyautocad+openpyxl处理cad文件。分享给大家供大家参考,具体如下: 示例1: from pyautocad import Autoca...

Python反射用法实例简析

本文实例讲述了Python反射用法。分享给大家供大家参考,具体如下: class Person: def __init__(self): self.name = "zjg...

django 使用 request 获取浏览器发送的参数示例代码

获取数据(四种方式) 1. url: 需要正则去匹配     url(r'^index/(num)/$',view.index)   &...

Pthon批量处理将pdb文件生成dssp文件

# -*- coding: utf-8 -*- """ Created on Sat Jun 20 19:36:34 2015 @author: chaofn """ import...