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计算一个文件里字数的方法。分享给大家供大家参考。具体如下: 这段程序从所给文件中找出字数来。 from string import * def countW...

python使用正则筛选信用卡

python使用正则筛选信用卡

本文实例为大家分享了python使用正则筛选信用卡的具体代码,供大家参考,具体内容如下 本文来源于两个简单的题目: 1.判断一对单词是否是" Anagrams " 2.判断信用卡是否合理...

Python复制文件操作实例详解

本文实例讲述了Python复制文件操作用法。分享给大家供大家参考,具体如下: 这里用python实现了一个小型的自动发版本的工具。这个“自动发版本”有点虚, 只是简单地把debug 目录...

python飞机大战 pygame游戏创建快速入门详解

python飞机大战 pygame游戏创建快速入门详解

本文实例讲述了python飞机大战 pygame游戏创建。分享给大家供大家参考,具体如下: 目标 项目准备 使用 pygame 创建图形窗口 理解 图像 并实现图像绘制...

python+opencv+caffe+摄像头做目标检测的实例代码

python+opencv+caffe+摄像头做目标检测的实例代码

首先之前已经成功的使用Python做图像的目标检测,这回因为项目最终是需要用摄像头的, 所以实现摄像头获取图像,并且用Python调用CAFFE接口来实现目标识别 首先是摄像头请选择支持...