zoukankan      html  css  js  c++  java
  • 利用Python批量重命名文件夹下文件

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    # -*- coding:utf8 -*-
    
    import os
    from string import digits
    
    
    class BatchRename():
    
        def __init__(self):
            #文件存放目录
            self.spath = 'Sensetime/'
    self.dpash='Sensetime-rename/'

         self.endpash='Sensetime-end/' def rename(self): filelist = os.listdir(self.spath) rename_fileList=os.listdir(self.dpash) total_num = len(filelist) i = 0 num = 0 for item in filelist: if item.endswith('.jpg'): if len(item.split("-")) == 2: src = os.path.join(os.path.abspath(self.spath), item) dst = os.path.join(os.path.abspath(self.dpash), item.split("-")[0] + '.jpg') try: print(src) os.rename(src, dst) print('converting %s to %s ...'% (item, item.split("-")[0] + '.jpg')) i = i + 1 except Exception as e: if e.args[0] == 17: print("####",item) dst = os.path.join(os.path.abspath(self.dpash), item.split("-")[0] + str(num) + '.jpg') os.rename(src, dst) num+=1 #continue else: print(item) print(len(item.split("-"))) print('total %d to rename & converted %d pngs'%(total_num, i)) #处理名字重名 重名数量统计入字典 def CheckDuplicateDname(self): i=0 name_dict={} rename_fileList = os.listdir(self.dpash) for item in rename_fileList: name=item.translate(str.maketrans('', '', digits)).split(".")[0] src = os.path.join(os.path.abspath(self.dpash), item) dst = os.path.join(os.path.abspath(self.endpash), name + '.jpg') if name not in name_dict.keys(): print(item,item not in name_dict) os.rename(src, dst) name_dict[name] = 1 i+=1 else: try: dst = os.path.join(os.path.abspath(self.endpash), name + str(name_dict[name]) +'.jpg') os.rename(src, dst) print('converting %s to %s ...' % (item, item.split("-")[0] + '.jpg')) i = i + 1 name_dict[name]+=1 except Exception as e: print(item) # contin print(name_dict) print("total:",i) print(sum(name_dict.values())) if __name__ == '__main__': demo = BatchRename() demo.rename() demo.CheckDuplicateDname()

     去除字符串中的数字:

    name=item.translate(str.maketrans('', '', digits)).split(".")[0]

  • 相关阅读:
    IBM X3650 M4服务器安装centos找不到硬盘的解决方法
    页面头部title、description、keywords标签的优化
    SEO优化之Title 和 Meta 标签
    WPA字典锦集
    PIN码计算锦集
    神经网络入门 第6章 识别手写字体
    神经网络入门 第5章 实现多层神经网络BP算法
    神经网络入门 第4章 神经网络可以模拟任意函数
    神经网络入门 第3章 S函数
    神经网络入门 第2章 编写第一个神经元
  • 原文地址:https://www.cnblogs.com/yinxin/p/11077994.html
Copyright © 2011-2022 走看看