Python 文件重命名工具代码

yipeiwu_com6年前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)

相关文章

zbar解码二维码和条形码示例

复制代码 代码如下:#!/usr/bin/env python# coding: u8import osimport zbarimport Imageimport urllibimpor...

celery4+django2定时任务的实现代码

网上有很多celery + django实现定时任务的教程,不过它们大多数是基于djcelery + celery3的; 或者是使用django_celery_beat配置较为繁琐的。...

Python中的上下文管理器和with语句的使用

Python2.5之后引入了上下文管理器(context manager),算是Python的黑魔法之一,它用于规定某个对象的使用范围。本文是针对于该功能的思考总结。 为什么需要上下文管...

postman传递当前时间戳实例详解

postman传递当前时间戳实例详解

请求动态参数(例如时间戳) 有时我们在请求接口时,需要带上当前时间戳这种动态参数,那么postman能不能自动的填充上呢。 我们可以使用postman的pre-request scrip...

Python 闭包的使用方法

Python 闭包的使用方法 嵌套函数中的非局部变量 在进入闭包之前,我们必须先了解一个嵌套函数和非局部变量。 在函数中定义另一个函数称为嵌套函数。嵌套函数可以访问包围范围内的变量。 在...