Python:批量重命名(图片、文本)

590次阅读
没有评论

Python:批量重命名(图片、文本)

1、前言

最近在家学习深度学习的caffe,在做某类识别的时候,自己采集到的图片,命名方式很乱,不利于caffe的模型训练, 所以采用python来实现对图片或者文本数据的批量重命名。

2、基本思路

调用到 python 的 os 模块,对某文件夹下的数据进行遍历(listdir),同时使用 rename 进行重命名操作即可。

3、实现效果

Python:批量重命名(图片、文本)

4、实现代码

代码如下:

# -*- coding:utf8 -*-
#usage:实现对图片的批量重命名

import os
class BatchRename():
#定义函数执行图片的路径  
    def __init__(self):
        self.path = '/home/nvidia/caffe/data/cheb/test/aodi'
#定义函数实现重命名操作
    def rename(self):
        filelist = os.listdir(self.path)
        total_num = len(filelist)
        i = 101
        for item in filelist:
            if item.endswith('.jpg'):
                src = os.path.join(os.path.abspath(self.path), item)
                dst = os.path.join(os.path.abspath(self.path), str(i) + '.jpg')
                try:
                    os.rename(src, dst)
                    print 'converting %s to %s ...' % (src, dst)
                    i = i + 1
                except:
                    continue
        print ('total %d to rename & converted %d jpgs' % (total_num, i))
#主函数调用
if __name__ == '__main__':
    demo = BatchRename()
    demo.rename()
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2020-03-06发表,共计1019字。
新手QQ群:570568346,欢迎进群讨论 Python51学习
评论(没有评论)