python实现多进程按序号批量修改文件名的方法示例

yipeiwu_com5年前Python基础

本文实例讲述了python实现多进程按序号批量修改文件名的方法。分享给大家供大家参考,具体如下:

说明

文件名命名方式如图,是数字序号开头,但是中间有些文件删掉了,序号不连续,这里将序号连续起来,总的文件量有40w+,故使用多进程

代码

import os
import re
from multiprocessing import Pool
def getAllFilePath(pathFolder,filter=[".jpg",".txt"]):
  #遍历文件夹下所有图片
  result=[]
  #maindir是当前搜索的目录 subdir是当前目录下的文件夹名 file是目录下文件名
  for maindir,subdir,file_name_list in os.walk(pathFolder):
    for filename in file_name_list:
      apath=os.path.join(maindir,filename)
      ext=os.path.splitext(apath)[1]#返回扩展名
      if ext in filter:
        result.append(apath)
  return result
def changName(filePath,changeNum):
  fileName=os.path.basename(filePath)
  dirName=os.path.dirname(filePath)
  pattern = re.compile(r'\d+')
  if len(pattern.findall(filePath))!=0:
    numInFileName=str(int(pattern.findall(fileName)[0])-changeNum)
    newFileName=pattern.sub(numInFileName,fileName)
    os.rename(filePath,os.path.join(dirName,newFileName))
    print('{1} is changed as {0}'.format(newFileName,fileName))
def changeNameByList(fileList,changNum):
  print('fileList len is:{}'.format(len(fileList)))
  for fileName in fileList:
    changName(fileName,changNum)
    print(fileName,' is done!')
if __name__ =='__main__':
  allFilePath=getAllFilePath(r'E:\Numberdata\4')
  n_total=len(allFilePath)
  n_process=8 #8线程
  #每段子列表长度
  length=float(n_total)/float(n_process)
  indices=[int(round(i*length)) for i in range(n_process+1)]
  sublists=[allFilePath[indices[i]:indices[i+1]] for i in range(n_process)]
  #生成进程池 
  p=Pool(n_process)
  for i in sublists:
    print("sublist len is {}".format(len(i)))
    p.apply_async(changeNameByList, args=(i,161130))
  p.close()
  p.join()

注意事项

  1. 多进程下python vscode终端debug不报错 注意可能潜在的bug
  2. os.rename()无法将文件命名成已经存在的文件,否则会报错

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python进程与线程操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》、《Python+MySQL数据库程序设计入门教程》及《Python常见数据库操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

Windows平台Python编程必会模块之pywin32介绍

Windows平台Python编程必会模块之pywin32介绍

在Windows平台上,从原来使用C/C++编写原生EXE程序,到使用Python编写一些常用脚本程序,成熟的模块的使用使得编程效率大大提高了。 不过,python模块虽多,也不可能满足...

Python 转换RGB颜色值的示例代码

题目:转换RBG颜色值 我们知道在网页中的颜色值设置都是用16进制的RGB来表示的,比如#FFFFFF,表示R:255,G:255,B:255的白色。 现在请设计一个函数可以转换RGB...

Django学习笔记之为Model添加Action

在使用Django自带的admin后台的时候,他提供了一些默认的指令可以对数据进行操作, 比如批量删除,修改等 同样的我们也可以添加自己的指令。 |- Django版本:1.8 |- P...

Python 装饰器深入理解

讲 Python 装饰器前,我想先举个例子,虽有点污,但跟装饰器这个话题很贴切。 每个人都有的内裤主要功能是用来遮羞,但是到了冬天它没法为我们防风御寒,咋办?我们想到的一个办法就是把内裤...

Python集合基本概念与相关操作实例分析

本文实例讲述了Python集合基本概念与相关操作。分享给大家供大家参考,具体如下: 集合的概念 集合是无序可变,元素不能重复。实际上,集合底层是字典实现,集合的所有元素都是字典 中的“键...