批量重命名文件 Python

最近工作需要,要批量重命名服務器上的文件,將之前文件名中有空格的全部都替換爲下劃線。
開始準備使用shell腳本,發現python實現更簡單。所以就寫了這個腳本。

 

  1. import os 
  2. import glob 
  3. import re 
  4. path="C:/test" # 批量化的初始位置 
  5. fileHandle = open ( 'C:/test/test.txt''w' ) #log記錄rename的信息 
  6.  
  7. def getthefile(path): 
  8.     for oldfn in glob.glob( path + os.sep + '*' ):  
  9.         if os.path.isdir( oldfn):# 查詢是含有子目錄 
  10.             getthefile( oldfn)  
  11.         else
  12.             if re.search(' ', oldfn): 
  13.                 fn=renamefile(oldfn) 
  14.                 if os.path.exists(fn): 
  15.                     index=1 
  16.                     while True
  17.                         filelist=fn.split('.'
  18.                         fn="%s%s%s.%s"%(filelist[0],"_",index,filelist[1]) 
  19.                         if os.path.exists(fn): 
  20.                             index=index+1 
  21.                             continue 
  22.                         break 
  23.                 fileHandle.write ("%s ===> %s\n"%(oldfn,fn)) 
  24.                 fileHandle.flush()   
  25.                 os.rename(oldfn,fn); 
  26.             else
  27.                 fileHandle.write ("%s Nospace!!\n"%(oldfn)) 
  28.                 fileHandle.flush()  
  29.                 continue 
  30. def renamefile(filename): 
  31.     return filename.replace(' ','_'
  32. if __name__ == '__main__':   
  33.     getthefile(path) 
  34.      
  35.  
  36.      
  37.  
  38.      

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章