小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

python批量修改文件夾內(nèi)所有圖片的名字

 pphsy 2018-12-14

聲明: 本文代碼非原創(chuàng), 原文鏈接沒(méi)找到,記錄一下,以防不時(shí)之需.

實(shí)現(xiàn)圖片處理的時(shí)候可能需要將圖片名字批量處理一下變成按順序如001.jpg... ...100.jpg的形式,但是我直接在網(wǎng)絡(luò)上爬取的圖片的命名好像是按照爬取的日期保存的,當(dāng)然你也可以在爬取文件中修改,但我們不考慮這種情況

我們就考慮當(dāng)前文件夾下的文件或者文件夾是亂序的,如下:

我們的目標(biāo)是修改成醬紫的:

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將文件名和后綴名字分開(kāi),返回元組
        # srcfilename表示只獲取元組首個(gè)元素,即文件名
        srcfilename = os.path.splitext(srcfile)[0]
        # sufix表示獲取元組第二個(gè)元素,即獲取后綴名
        sufix = os.path.splitext(srcfile)[1]
        #根據(jù)目錄下具體的文件數(shù)修改%號(hào)后的值,"%04d"最多支持9999
        destfile = srcdir + "http://"+ prefix + "%04d"%(index) + postfix
        srcfile = os.path.join(srcdir, srcfile)
        # os.rename() 方法用于命名文件或目錄,從 src  dst,如果dst是一個(gè)存在的目錄, 將拋出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后綴

修改圖片的名字:

我的圖片讀取的時(shí)候是格式是"date_v000_1.jpg",我要修改成"set00_v000_1.jpg"也就是只修改部分,趕緊寫(xiě)下了記住這個(gè)以后再修改個(gè)圖片數(shù)據(jù)集名字什么的都不怕了

code:

import os
# 圖片輸入路徑
path = '/media/li_hiayu/D/Caltech/JPEG'
# 圖片輸出路徑,用來(lái)存儲(chǔ)修改名字后圖片的位置,當(dāng)然你也可以覆蓋在pathoutpath = '/media/li_hiayu/D/Caltech/JPEGImages'

if not os.path.exists(outpath):
   os.makedirs(outpath)

# os.listdir(path)歷遍path路徑并獲取文件名存儲(chǔ)到列表中并返回
for img in os.listdir(path):
    # 這一句hin重要,是個(gè)隱藏文件... .. .
    if img != '.DS_Store':
   # os.path.splitext將文件名拆分為名字和后綴名,可以打印出來(lái)看一下
        name = os.path.splitext(img)
   # 獲取拆分后的第一個(gè)元素(文件名)也就是“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
   # 獲取拆分后的第二個(gè)元素(后綴名)
        four_segment = name[1] # ".jpg"
        str = "set00"
   # 補(bǔ)全圖片路徑
        org_name = os.path.join(path,img)
   # 補(bǔ)全修改后的路徑以及文件名
        changed_name = outpath+"http://"+str+"_"+second_segment+"_"+three_segment+four_segment
   # os.rename(old_one,new_one)
        os.rename(org_name,changed_name)
提醒:修改之后,原來(lái)文件夾中的圖片就完全轉(zhuǎn)移到outpath中,也就是JPEG就清空了

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶(hù)發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買(mǎi)等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶(hù) 評(píng)論公約

    類(lèi)似文章 更多