????:這篇文章主要介紹了Python實現(xiàn)批量更換指定目錄下文件擴展名的方法,結合完整實例分析了Python批量修改文件擴展名的技巧,并對比分析了shell命令及scandir的兼容性代碼,需要的朋友可以參考下本文實例講述了Python實現(xiàn)批量更換指定目錄下文件擴展名的方法。分享給大家供大家參考,具體如下:#encoding=utf-8 #author: walker #date: 2
這篇文章主要介紹了Python實現(xiàn)批量更換指定目錄下文件擴展名的方法,結合完整實例分析了Python批量修改文件擴展名的技巧,并對比分析了shell命令及scandir的兼容性代碼,需要的朋友可以參考下
本文實例講述了Python實現(xiàn)批量更換指定目錄下文件擴展名的方法。分享給大家供大家參考,具體如下:
#encoding=utf-8 #author: walker #date: 2013-12-06 #function: 深度遍歷指定目錄,更換指定擴展名 import os import 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_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-
更多關于Python實現(xiàn)批量更換指定目錄下文件擴展名的方法請關注PHP中文網(wǎng)(ipnx.cn)其他文章!