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 requests库中的代理实例讲解

直接上代码: #request代理(proxy) """ 1.启动代理服务器Heroku,相当于aliyun 2.在主机1080端口启动Socks 服务 3.将请求转发到1080端口...

举例详解Python中yield生成器的用法

yield是生成的意思,但是在python中则是作为生成器理解,生成器的用处主要可以迭代,这样简化了很多运算模型(还不是很了解是如何简化的)。 yield是一个表达式,是有返回值的. 当...

tensorflow tf.train.batch之数据批量读取方式

在进行大量数据训练神经网络的时候,可能需要批量读取数据。于是参考了这篇文章的代码,结果发现数据一直批量循环输出,不会在数据的末尾自动停止。 然后发现这篇博文说slice_input_pr...

python3 对list中每个元素进行处理的方法

在写代码过程中我们常常可能会遇到这样一种情况,要对一个list中的每个元素做同样的操作时,两种方法 方法一:循环遍历每个元素 话不多说,上代码 a = [1,2,3] for i...

python使用Flask框架获取用户IP地址的方法

本文实例讲述了python使用Flask框架获取用户IP地址的方法。分享给大家供大家参考。具体如下: 下面的代码包含了html页面和python代码,非常详细,如果你正使用Flask,也...