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中用于求最小值的min()方法

 min()方法返回它的参数最小值:最接近负无穷大的值。 语法 以下是min()方法的语法: min( x, y, z, .... ) 参数  &nb...

python使用matplotlib库生成随机漫步图

python使用matplotlib库生成随机漫步图

本教程使用python来生成随机漫步数据,再使用matplotlib将数据呈现出来 开发环境 操作系统: Windows10 IDE: Pycharm 2017.1.3 Python...

Python使用CMD模块更优雅的运行脚本

本文实例讲述了Python使用CMD模块更优雅的运行脚本的方法。分享给大家供大家参考。具体分析如下: 平时由于经常给测试人员调试一些东西,虽然写了一些脚本,感觉还是不方便。 python...

Python pandas常用函数详解

本文研究的主要是pandas常用函数,具体介绍如下。 1 import语句 import pandas as pd import numpy as np import matplot...

Python3.5 Json与pickle实现数据序列化与反序列化操作示例

Python3.5 Json与pickle实现数据序列化与反序列化操作示例

本文实例讲述了Python3.5 Json与pickle实现数据序列化与反序列化操作。分享给大家供大家参考,具体如下: 1、Json:不同语言之间进行数据交互。 (1)JSON数据序列化...