本文實例講述了Python實現批量更換指定目錄下文件擴展名的方法。分享給大家供大家參考,具體如下:
#encoding=utf-8#author: walker#date: 2013-12-06#function: 深度遍歷指定目錄,更換指定擴展名import osimport os.path#讀入指定目錄并轉換為絕對路徑rootdir = raw_input('root dir:/n')rootdir = os.path.abspath(rootdir)print('absolute path:/n' + rootdir)#讀入原擴展名并標準化old_ext = raw_input('old extension:/n')old_ext = old_ext.strip()if old_ext[0] != '.': old_ext = '.' + old_ext#讀入新擴展名并標準化new_ext = raw_input('new extension:/n')new_ext = new_ext.strip()if new_ext[0] != '.': new_ext = '.' + new_extfor parent, dirnames, filenames in os.walk(rootdir): for filename in filenames: pathfile = os.path.join(parent, filename) if pathfile.endswith(old_ext): new_pathfile = os.path.splitext(pathfile)[0] + new_ext print('=======================================================') print(pathfile) print('-------------------------------------------------------') print(new_pathfile) print('=======================================================') os.rename(pathfile, new_pathfile)PS:上述功能一個shell命令也可以實現
#將后綴.ini換成.txt#路徑名可以是相對路徑或絕對路徑find 路徑名 | rename 's//.ini$//.txt/'
注意,上面的rename命令是perl版的rename命令。
PS2:scandir的兼容代碼。
# Use the built-in version of scandir/walk if possible, otherwise# use the scandir module versiontry: from os import scandir, walk #python3.5+except ImportError: from scandir import scandir, walk #python3.4-
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python文件與目錄操作技巧匯總》、《Python文本文件操作技巧匯總》、《Python URL操作技巧總結》、《Python圖片操作技巧總結》、《Python數據結構與算法教程》、《Python Socket編程技巧總結》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答
圖片精選