python 批量图片重命名脚本

ziDANe 撰写  

经常从网上保存图片的时候都是随手另存为,保存图片的目录凌乱不堪。
写了个脚本按照文件保存的顺序进行排序,并按照保存的时间顺序进行重命名,这样图片基本可以按照分类保存,即一类的图片是连续保存的。


#!/usr/bin/env/python
#pic sort with create time for python 2.0
''' This is a tool for sort and  rename the pictures by create time
test in python 2.6 ,windows xp
--------------------------

http://d-up.org/man

zidane
--------------------------
'''
import os
def renameEx(old,new):
    print 'begin to rename',old,new
    new2=''
    for i in range(0,len(new)-1,2):
        a=new[i:i+2]
        if a!='\xa1@':
            new2+=a;
    print 'new name =',new2
    if new2!=old:
        os.rename(old,new2)
        print 'rename',old,'to',new2

def picsort(dir):
    cwd=dir
    os.chdir(cwd)
    path=dir+"\\"
    file_dir=os.listdir(cwd)
    files=[]
    dirs=[]
    time_file=[]
    ext = ('.jpg','.gif','.bmp','png')
    fileCount=0
    picCount=0
    dirCount=0
#list files and dirs in 'file_dir'
    for eachOne in file_dir:
        if os.path.isfile(eachOne):
            #filefull=path+eachOne
            files.append(eachOne)
            fileCount+=1
        else:
            dir_full=path+eachOne
            dirs.append(dir_full)
            dirCount+=1
    print "there have %d files" %fileCount,
    print "and %d directory" %dirCount
    print "****************************"
 #list pics in 'files'
    for eachPic in files:
        if os.path.splitext(eachPic)[1] in ext:
            timeTemp=os.path.getmtime(eachPic)
            time_file.append([timeTemp,eachPic])
            picCount+=1
        else:
            files.remove(eachPic)

    time_file.sort()
    #rename the files
    file_name=1
    for eachOne in time_file:
        print eachOne
        print "------------"
        old_name,f_ext=os.path.splitext(eachOne[1])
        newname="%05d" %file_name
        newname+=f_ext
        os.rename(eachOne[1],newname)
        file_name+=1

    for eachOne in dirs:
        print eachOne
        picsort(eachOne)

if __name__=="__main__":
    dir_path=raw_input("Enter the dir name:")
    picsort(dir_path)
    print "All pic have sorted!!"

条评论

  1. ZEND
    发表了 2010年04月25日 在 9:33 下午 | 永久链接

    这个太有用了,谢谢啊

发表评论

Your email is never shared.