python 批量修改文件后缀名(示例)

发布时间:2019-12-27编辑:脚本学堂
分享一例python实现批量修改文件后缀名的代码,学习下python修改文件后缀的方法,有需要的朋友参考下。

例子,python批量修改文件后缀
代码:
 

复制代码 代码示例:

importos,string

defs_rename(path,old_ext,new_ext):
    for(path, dirs, files) in os.walk(path):
        for filename in  files:
            ext=os.path.splitext(filename)[1]
            if(cmp(ext,old_ext)==0):
                newname=filename.replace(old_ext,new_ext)
                oldpath=path+""+filename
                newpath=path+""+newname
                print"oldpath:"+oldpath+""
                print"newpth:"+newpath+""
                try:
                    os.rename(oldpath, newpath)
                exceptValueError:
                    print"Error when rename the file "+ oldpath
                exceptNameError:
                    print"Error when rename the file "+ oldpath
                exceptOSError:
                    #print OSError
                    printnewpath + " The file is already exist!"