實現(xiàn)圖片處理的時候可能需要將圖片名字批量處理一下變成按順序如001.jpg... ...100.jpg的形式,但是我直接在網(wǎng)絡(luò)上爬取的圖片的命名好像是按照爬取的日期保存的,當然你也可以在爬取文件中修改,但我們不考慮這種情況
我們就考慮當前文件夾下的文件或者文件夾是亂序的,如下:
我們的目標是修改成醬紫的:
code:
import sys, string, os, shutil def RenameFiles(prefix,srcdir,postfix): # os.listdir(path)歷遍所有文件路勁,返回為列表 srcfiles = os.listdir(srcdir) index = 1 for srcfile in srcfiles: # os.path.splitext將文件名和后綴名字分開,返回元組 # srcfilename表示只獲取元組首個元素,即文件名 srcfilename = os.path.splitext(srcfile)[0] # sufix表示獲取元組第二個元素,即獲取后綴名 sufix = os.path.splitext(srcfile)[1] #根據(jù)目錄下具體的文件數(shù)修改%號后的值,"%04d"最多支持9999 destfile = srcdir + "http://"+ prefix + "%04d"%(index) + postfix srcfile = os.path.join(srcdir, srcfile) # os.rename() 方法用于命名文件或目錄,從 src 到 dst,如果dst是一個存在的目錄, 將拋出OSError os.rename(srcfile, destfile) index += 1 print (destfile) srcdir = "./test_name" prefix = "前綴" postfix = "后綴" RenameFiles(prefix,srcdir,postfix)
output:
./test_name//前綴0001后綴
./test_name//前綴0002后綴
./test_name//前綴0003后綴
./test_name//前綴0004后綴
修改圖片的名字:
我的圖片讀取的時候是格式是"date_v000_1.jpg",我要修改成"set00_v000_1.jpg"也就是只修改部分,趕緊寫下了記住這個以后再修改個圖片數(shù)據(jù)集名字什么的都不怕了
code:
import os # 圖片輸入路徑 path = '/media/li_hiayu/D/Caltech/JPEG' # 圖片輸出路徑,用來存儲修改名字后圖片的位置,當然你也可以覆蓋在path中 outpath = '/media/li_hiayu/D/Caltech/JPEGImages' if not os.path.exists(outpath): os.makedirs(outpath) # os.listdir(path)歷遍path路徑并獲取文件名存儲到列表中并返回 for img in os.listdir(path): # 這一句hin重要,是個隱藏文件... .. . if img != '.DS_Store': # os.path.splitext將文件名拆分為名字和后綴名,可以打印出來看一下 name = os.path.splitext(img) # 獲取拆分后的第一個元素(文件名)也就是“data_v000_1” img_segment = name[0] # 再拆分一次 name_segment = img_segment.split("_") first_segment = name_segment[0] #data second_segment = name_segment[1]#v000 three_segment = name_segment[2]# 1 # 獲取拆分后的第二個元素(后綴名) four_segment = name[1] # ".jpg" str = "set00" # 補全圖片路徑 org_name = os.path.join(path,img) # 補全修改后的路徑以及文件名 changed_name = outpath+"http://"+str+"_"+second_segment+"_"+three_segment+four_segment # os.rename(old_one,new_one) os.rename(org_name,changed_name)提醒:修改之后,原來文件夾中的圖片就完全轉(zhuǎn)移到outpath中,也就是JPEG就清空了