为何list.append(openpyxl对象)可行,list[index]=openpyxl对象却报错?
批量加载Excel文件的Python函数索引赋值报错原因
你的代码如下:
def batchLoader(files, openMode="o"): #loads files out of the array of files it is passed. Modes are either 'o'pen or 'n'ew file. if len(openMode)==1: #lazy mode applier openMode=openMode*len(files) excelObjects=[] #array of excel objects we are gonna load for file, mode, index in zip(files, openMode, range(0,len(files))): if mode=="n": #if in newmode, create a blank file excelObjects[index]=openpyxl.Workbook() excelObjects[index].save(file) print(file,mode,index) try: currentFile=openpyxl.load_workbook(file) #load the requested file excelObjects.append(currentFile) print('he') except: print('ho') fileErrorHandler(file, 'could not be loaded') sys.exit() fileErrorHandler(file,'has been loaded') return excelObjects
报错原因
核心问题是空列表不能直接通过索引赋值:
你初始化的excelObjects是空列表[],Python的列表不允许给不存在的索引位置赋值。比如第一次循环index=0时,列表长度为0,根本没有excelObjects[0]这个位置,直接赋值就会抛出IndexError: list assignment index out of range。
而append方法是在列表末尾添加新元素,不管列表当前长度,所以try块里的写法不会报错。
两种修正思路
- 用append替代索引赋值
把mode=="n"分支的代码改成直接添加新工作簿到列表,同时注意跳过后续重复加载的逻辑:
if mode=="n": wb = openpyxl.Workbook() wb.save(file) excelObjects.append(wb) # 跳过后续的load_workbook步骤,避免重复添加 print(file,mode,index) fileErrorHandler(file,'has been loaded') continue
- 先初始化列表为指定长度的占位符
如果一定要用索引赋值,先把excelObjects初始化为和文件数量相同的占位符列表,确保每个索引位置都存在:
# 替换原来的excelObjects=[] excelObjects = [None] * len(files)
这样后续就可以直接用excelObjects[index] = ...赋值了。
内容的提问来源于stack exchange,提问作者Wyatt Sutcliffe
相关产品推荐
相关产品推荐

