python代码批量更改文件后缀

#-------------------------------------------------------------------------------
# Name:        ChangeFilesExtension
# Purpose:     Try to change extension of a file from one to others
#
# Author:      ankier
#
# Created:     30/08/2012
# Copyright:   (c) ankier 2012
# Licence:     <your licence>
#-------------------------------------------------------------------------------

# -*- coding: cp936 -*-
import os
path = 'D:\\Test'

def ChangeFilesExtension(path,oldExtension, newExtension):
    for file in os.listdir(path):
        oldFullName =os.path.join(path,file)
        if os.path.isfile(oldFullName):
            fileExtension = os.path.splitext(file) #返回 (filename, extension) 元组

            if fileExtension[1] == oldExtension:
                newname=fileExtension[0] + newExtension
                os.rename(oldFullName,os.path.join(path,newname))
                print file,'ok'

def main():
    ChangeFilesExtension(path, '.bin', '.png')

if __name__ == '__main__':
    main()

posted on 2012-08-30 22:06  |残阳|露  阅读(246)  评论(0编辑  收藏  举报

导航