您的位置:首页 > 编程语言 > Python开发

python os模块实例(批量修改图片名称)

2016-05-26 00:00 761 查看
摘要: 昨天学习了os模块常用函数,今天写一个实例来巩固下;主要实现批量修改目录下全部图片的文件名,给文件名前面加上‘shm’。利用递归,也可以处理子目录图片。

# -*- coding:utf-8 -*-
import os
import time
def changeImgName(path):
global i
if not os.path.isdir(path) and not os.path.isfile(path):
return False
if os.path.isfile(path):
filePath = os.path.split(path)           #分割出目录与文件
fileMsg = os.path.splitext(filePath[1]) #分割出文件与文件扩展名
fileExt = fileMsg[1]                     #取出后缀名(列表切片操作)
fileName = fileMsg[0]                       #取出文件名
imgExtList = ['bmp','jpeg','gif','png','jpg'] #常见文件名
if fileExt.strip('.') in imgExtList:
os.rename(path, filePath[0]+os.sep+'sm'+fileName.replace('shm', '')+fileExt) #重命名
i += 1
elif os.path.isdir(path):#递归处理
for x in os.listdir(path):
changeImgName(os.path.join(path, x)) #os.path.join()路径处理

time.clock()
i = 0
changeImgName('E:\\image')
print('程序运行耗时:%0.2f'%(time.clock()))
print('总共处理了 %s 张图片'%(i))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python os