博客网站的建设,自助建网站平台怎么收费,百度站长链接提交平台,兰州企业网络优化服务本文实例讲述了python实现多进程按序号批量修改文件名的方法。分享给大家供大家参考#xff0c;具体如下#xff1a;说明文件名命名方式如图#xff0c;是数字序号开头#xff0c;但是中间有些文件删掉了#xff0c;序号不连续#xff0c;这里将序号连续起来#xff0c;…本文实例讲述了python实现多进程按序号批量修改文件名的方法。分享给大家供大家参考具体如下说明文件名命名方式如图是数字序号开头但是中间有些文件删掉了序号不连续这里将序号连续起来总的文件量有40w故使用多进程代码import osimport refrom multiprocessing import Pooldef 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:apathos.path.join(maindir,filename)extos.path.splitext(apath)[1]#返回扩展名if ext in filter:result.append(apath)return resultdef changName(filePath,changeNum):fileNameos.path.basename(filePath)dirNameos.path.dirname(filePath)pattern re.compile(r\d)if len(pattern.findall(filePath))!0:numInFileNamestr(int(pattern.findall(fileName)[0])-changeNum)newFileNamepattern.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__:allFilePathgetAllFilePath(rE:\Numberdata\4)n_totallen(allFilePath)n_process8 #8线程#每段子列表长度lengthfloat(n_total)/float(n_process)indices[int(round(i*length)) for i in range(n_process1)]sublists[allFilePath[indices[i]:indices[i1]] for i in range(n_process)]#生成进程池pPool(n_process)for i in sublists:print(sublist len is {}.format(len(i)))p.apply_async(changeNameByList, args(i,161130))p.close()p.join()注意事项多进程下python vscode终端debug不报错 注意可能潜在的bugos.rename()无法将文件命名成已经存在的文件否则会报错更多关于Python相关内容感兴趣的读者可查看本站专题《Python进程与线程操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》、《PythonMySQL数据库程序设计入门教程》及《Python常见数据库操作技巧汇总》希望本文所述对大家Python程序设计有所帮助。本文标题: python实现多进程按序号批量修改文件名的方法示例本文地址: http://www.cppcns.com/jiaoben/python/296112.html