1. 程式人生 > >Python批量檔案字尾修改

Python批量檔案字尾修改

還沒加重新命名功能的,只是列出所有檔案

#替換所有jpg格式的為png格式
import os

def filenameReplace(dir):
        #得到的只是檔名,要和資料夾名字拼起來
        files = os.listdir(dir)
        for file in files:
                absolutePath = dir +os.path.sep+ file
                if os.path.isfile(absolutePath):
                        print('file:',absolutePath)
                else:
                        filenameReplace(absolutePath)


dir = '進擊的巨人漫畫'

dirs = os.listdir(dir)

filenameReplace(dir)

執行重新命名版

#替換所有jpg格式的為png格式
import os

def filenameReplace(dir):
        #得到的只是檔名,要和資料夾名字拼起來
        files = os.listdir(dir)
        for file in files:
                absolutePath = dir +os.path.sep+ file
                if os.path.isfile(absolutePath):
                        newpath = absolutePath.replace(".jpg",".png")
                        print('file:',absolutePath,"->",newpath)
                        os.rename(absolutePath,newpath)

                else:
                        filenameReplace(absolutePath)


dir = '進擊的巨人漫畫'

dirs = os.listdir(dir)

filenameReplace(dir)