Python批量修改文件后缀的脚本

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

本节内容:
python实现文件后缀名的批量修改。

使用方法:s_rename(路径,原后缀,新后缀)

代码:
 

复制代码 代码示例:
#coding:gbk
#code By Neeao
#2009-09-15
import os,string 
 
def s_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)
                except ValueError:
                    print "Error when rename the file " + oldpath
                except NameError:
                    print "Error when rename the file " + oldpath
                except OSError:
                    #print OSError
                    print newpath + " The file is already exist!"
if __name__ == '__main__':
    s_rename("F:code",".ph",".pl")
    #print "test"