這操作很騷,必須會用。
1.目的:
想把files文件夾下的excel文件改掉,這裡假設改為’fileA.xlsx’,’fileB.xlsx’,如何使用python自動更改。
file1.xlsx,file.xlsx改為fileA.xlsx,fileB.xlsx
2.修改手段:
利用os.rename模塊,以及前面講的glob模塊。
首先獲取文件夾下的excel文件:
import glob,os
changeFileType = '*.xlsx'
path = 'files'
def getFileLst(path,changeFileType):
fileLst = glob.glob(os.path.join(path,changeFileType))
return fileLst
fileList = getFileLst(path,changeFileType)輸出fileList:[‘files\file1.xlsx’, ‘files\file2.xlsx’]
修改代碼:
newNameLst = ['fileA.xlsx','fileB.xlsx']
for oldName,newName in zip(fileList,newNameLst):
newName = os.path.join(path,newName)
os.rename(oldName, newName)效果:
修改後的結果
該操作可用於批量修改文件名稱。

原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/226865.html
微信掃一掃
支付寶掃一掃