这操作很骚,必须会用。
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)
效果:
修改后的结果
该操作可用于批量修改文件名称。

