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)

相关文章

浅谈Python3识别判断图片主要颜色并和颜色库进行对比的方法

浅谈Python3识别判断图片主要颜色并和颜色库进行对比的方法

【更新】主要提供两种方案: 方案一:(参考网上代码,感觉实用性不是很强)使用PIL截取图像,然后将RGB转为HSV进行判断,统计判断颜色,最后输出RGB值 方案二:使用opencv库函数...

python多线程并发及测试框架案例

这篇文章主要介绍了python多线程并发及测试框架案例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1、循环创建多个线程,并通过循环...

Python 用户登录验证的小例子

复制代码 代码如下:#!/usr/bin/python#coding=gbk class User:    def __init__(self,userna...

获取Pytorch中间某一层权重或者特征的例子

问题:训练好的网络模型想知道中间某一层的权重或者看看中间某一层的特征,如何处理呢? 1、获取某一层权重,并保存到excel中; 以resnet18为例说明: import t...

python操作日志的封装方法(两种方法)

前言 今天就简单的对日志做个封装,实际工作中直接拿去用吧 方法1 """ ------------------------------------ @Time : 2019/5/22...