当前位置:编程学习 > 网站相关 >>

Python批量修改文件后缀脚本

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

  1. #coding:gbk 
  2. #code By Neeao 
  3. #2009-09-15 
  4. import os,string 
  5.  
  6.  
  7. def s_rename(path,old_ext,new_ext): 
  8.     for (path, dirs, files) in os.walk(path): 
  9.         for filename in files: 
  10.             ext=os.path.splitext(filename)[1] 
  11.             if (cmp(ext,old_ext)==0): 
  12.                 newname=filename.replace(old_ext,new_ext) 
  13.                 oldpath=path+"\"+filename 
  14.                 newpath=path+"\"+newname 
  15.                 print "oldpath:"+oldpath+"" 
  16.                 print "newpth:"+newpath+"" 
  17.                 try: 
  18.                     os.rename(oldpath, newpath) 
  19.                 except ValueError: 
  20.                     print "Error when rename the file " + oldpath 
  21.                 except NameError: 
  22.                     print "Error when rename the file " + oldpath 
  23.                 except OSError: 
  24.                     #print OSError 
  25.                     print newpath + " The file is already exist!" 
  26. if __name__ == __main__: 
  27.     s_rename("F:\code",".ph",".pl") 
  28.     #print "test" 
补充:Web开发 , Python ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,