如何使用python批量修改檔名稱?

2021-08-20 09:33:15 字數 813 閱讀 8580

import sys, string, os, shutil

#輸入目錄名和字首名,重新命名後的名稱結構類似prefix_0001

#首先新建乙個方法renamefiles

def renamefiles(srcdir, prefix):

#讀取資料夾中的資料

srcfiles = os.listdir(srcdir)

index = 1

#迴圈需要修改的資料夾

for srcfile in srcfiles:

#擷取迴圈出的檔名部分

srcfilename = os.path.splitext(srcfile)[0][1:]

#擷取公共的字尾名

sufix = os.path.splitext(srcfile)[1]

#按照條件修改檔名並賦值destfile,給根據目錄下具體的檔案數修改%號後的值,"%04d"最多支援9999

destfile = srcdir + "//" + prefix + "_%04d"%(index) + sufix

#將新的檔名返回給srcfile

srcfile = os.path.join(srcdir, srcfile)

os.rename(srcfile, destfile)

index += 1

print ("destfile")

srcdir = "c:/users/desktop/wangjy\json15"

prefix = "alertfile"

#呼叫該方法

renamefiles(srcdir, prefix)

使用python批量修改檔名

在工作中有時候會遇到多個檔名格式不對的情況,需要一一修改,例如從test1.py,test2.py,testn.py改為test 1.py,test 2.py,test n.py的情況,如果檔案數量少手動改改就算了,但是檔案多的話,就不想手動改了,我現在本著重複的事情盡量用 實現,就想著肯定可以通過...

批量解壓 python程式設計 批量解壓RAR檔案

本文實現rar批量解壓的功能,通過python指令碼呼叫winrar.exe解壓檔案時似乎不會再有廣告框彈出。通過python呼叫winrar.exe程式實現rar檔案的批量解壓,如下 import argparseimport osclass rarextractor def init self,...

python批量修改檔案指令碼

最近在做訓練集,好多未排序,記錄一下重新命名的 import osimport reimport sys 以下為目標資料夾與當前資料夾相同的示例 defrename filelist os.listdir r d file label 當前 資料夾,儲存檔案的資料夾 currentpath os.g...