批量重命名文件 Python

最近工作需要,要批量重命名服務器上的文件,將之前文件名中有空格的全部都替換爲下劃線。

開始準備使用shell腳本,發現python實現更簡單。所以就寫了這個腳本。

import os 
import glob 
import re 
path="C:/test" # 批量化的初始位置 
fileHandle = open ('C:/test/test.txt', 'w' ) #log記錄rename的信息 
 
def getthefile(path): 
    for oldfn in glob.glob(path + os.sep + '*' ):  
        if os.path.isdir(oldfn):# 查詢是含有子目錄 
            getthefile(oldfn)  
        else: 
            if re.search(' ', oldfn): #查詢此文件目錄是否包含空格
                fn=renamefile(oldfn) 
                if os.path.exists(fn): 
                    index=1 
                    while True: 
                        filelist=fn.split('.') #爲了防止有多個文件重命名之後,文件名一樣。所以添加index區分
                        fn="%s%s%s.%s"%(filelist[0],"_",index,filelist[1]) 
                        if os.path.exists(fn): 
                            index=index+1 
                            continue 
                        break 
                fileHandle.write ("%s ===> %s\n"%(oldfn,fn)) #將重命名記錄在日誌文件中
                fileHandle.flush()   
                os.rename(oldfn,fn) #重命名文件
            else: 
                fileHandle.write ("%s Nospace!!\n"%(oldfn)) 
                fileHandle.flush()  
                continue 
def renamefile(filename): 
    return filename.replace(' ','_') 
if __name__ == '__main__':   
    getthefile(path) #主函數


發佈了29 篇原創文章 · 獲贊 3 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章