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)

相关文章

github配置使用指南

1.建立项目,进入项目文件夹 2.初始化ssh key 参见官网指南.(本机生成一对key,public key传到官网sshkey下面) https://help.github.com...

springboot配置文件抽离 git管理统 配置中心详解

springboot配置文件抽离,便于服务器读取对应配置文件,避免项目频繁更改配置文件,影响项目的调试与发布 1.创建统一配置中心项目conifg 1)pom配置依赖 <pa...

numpy中三维数组中加入元素后的位置详解

numpy中三维数组中加入元素后的位置详解

今天做数据处理时,遇到了从三维数组中批量加入二维数组的需求。其中三维数组在深度学习的特征数据处理时经常会使用到,所以读者有必要对该小知识点做到清楚了解并掌握。现对三维数组中的元素位置结合...

python中numpy.zeros(np.zeros)的使用方法

翻译: 用法:zeros(shape, dtype=float, order='C') 返回:返回来一个给定形状和类型的用0填充的数组; 参数:shape:形状 dtype:数据类型,可...

Ubuntu下使用python读取doc和docx文档的内容方法

读取docx文档 使用的包是python-docx 1. 安装python-docx包 sudo pip install python-docx 2. 使用python-docx...