Python實現(xiàn)批量更換指定目錄下文件擴展名的方法
本文實例講述了Python實現(xiàn)批量更換指定目錄下文件擴展名的方法。分享給大家供大家參考,具體如下:
#encoding=utf-8 #author: walker #date: 2013-12-06 #function: 深度遍歷指定目錄,更換指定擴展名 import os import os.path #讀入指定目錄并轉(zhuǎn)換為絕對路徑 rootdir = raw_input('root dir:\n') rootdir = os.path.abspath(rootdir) print('absolute path:\n' + rootdir) #讀入原擴展名并標(biāo)準化 old_ext = raw_input('old extension:\n') old_ext = old_ext.strip() if old_ext[0] != '.': old_ext = '.' + old_ext #讀入新擴展名并標(biāo)準化 new_ext = raw_input('new extension:\n') new_ext = new_ext.strip() if new_ext[0] != '.': new_ext = '.' + new_ext for 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命令也可以實現(xiàn)
#將后綴.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 version try: from os import scandir, walk #python3.5+ except ImportError: from scandir import scandir, walk #python3.4-
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python文件與目錄操作技巧匯總》、《Python文本文件操作技巧匯總》、《Python URL操作技巧總結(jié)》、《Python圖片操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
keras實現(xiàn)基于孿生網(wǎng)絡(luò)的圖片相似度計算方式
這篇文章主要介紹了keras實現(xiàn)基于孿生網(wǎng)絡(luò)的圖片相似度計算方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06使用python畫出邏輯斯蒂映射(logistic map)中的分叉圖案例
這篇文章主要介紹了使用python畫出邏輯斯蒂映射(logistic map)中的分叉圖案例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12