本文實例講述了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()
注意事項
多進程下python vscode終端debug不報錯 注意可能潛在的bug
os.rename()無法將文件命名成已經存在的文件,否則會報錯
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python進程與線程操作技巧總結》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》、《Python+MySQL數據庫程序設計入門教程》及《Python常見數據庫操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
本文標題: python實現多進程按序號批量修改文件名的方法示例
本文地址: http://www.cppcns.com/jiaoben/python/296112.html