python获取文件后缀名及批量更新目录下文件后缀名的方法

#coding:utf-8

import os

#获取文件后缀名称
dict = {}   #存放文件后缀名
path = r'E:\test\'

for  dirpath,dirnames,filenames in os.walk(path):
    for filename in filenames:
        sufix = os.path.splitext(filename)[1][1:]
        if dict.has_key(sufix):
            dict[sufix]+=1
        else:
            dict[sufix] = 1

for item in dict.items():
    print '%s:%s' %item

#查找遍历指定文件路径下指定后缀名的文件实例
for dirpath,dirnames,filenames in os.walk(path):
    for filename in filenames:
        if os.path.splitext(filename)[1] == '.txt':
            filepath = os.path.join(dirpath,filename)
            print 'file:'+filepath

def swap_extensions(dir,before,after):
    if before[:1] != '.':   #如果参数后缀没有’.'则加上
        before='.'+before
    thelen = -len(before)
    if after[:1] != '.':
        after = '.'+after
    for dirpath,dirnames,filenames in os.walk(path):
        for oldfile in filenames:
            if oldfile[thelen:] == before:
                oldfile = os.path.join(path,oldfile)
                newfile = oldfile[:thelen]+after
                os.rename(oldfile,newfile)
                print oldfile+' changed to '+newfile

if __name__ == '__main__':
    import sys
    if len(sys.argv) != 4:
        print 'Usage:swap_extension.py rootdir before after'
        sys.exit(1)
    swap_extensions(sys.argv[1],sys.argv[2],sys.argv[3])
    

posted @ 2015-05-23 22:07  星空天宇  阅读(103)  评论(0编辑  收藏  举报