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

yipeiwu_com7年前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程序设计有所帮助。

相关文章

python调用c++ ctype list传数组或者返回数组的方法

示例1: pycallclass.cpp: #include <iostream> using namespace std; typedef unsigned char...

解决Python selenium get页面很慢时的问题

解决Python selenium get页面很慢时的问题

driver.get("url")等到页面全部加载渲染完成后才会执行后续的脚本。 在执行脚本时,driver.get("url") ,如果当前的url页面内容较多加载特别慢,很费时间,但...

Python简单定义与使用字典dict的方法示例

Python简单定义与使用字典dict的方法示例

本文实例讲述了Python简单定义与使用字典的方法。分享给大家供大家参考,具体如下: #coding=utf8 print ''''' Python中的字典映射数据类型是由键值对构成...

Python的Socket编程过程中实现UDP端口复用的实例分享

关于端口复用 一个套接字不能同时绑定多个端口,如果客户端想绑定端口号,一定要调用发送信息函数之前绑定( bind )端口,因为在发送信息函数( sendto, 或 write ),系统会...

django框架如何集成celery进行开发

django框架如何集成celery进行开发

上一篇已经介绍了celery的基本知识,本篇以一个小项目为例,详细说明django框架如何集成celery进行开发。 本系列文章的开发环境: window 7 + python2.7...