[英]Read multiple files using openpyxl
I have a list with a few filenames我有一个包含几个文件名的列表
ListOfFiles = ['filename1.xlsm', 'filename2.xlsm',...]
What I want to do, is to load these files in an automated way.我想要做的是以自动方式加载这些文件。 So I wrote the following:
所以我写了以下内容:
from openpyxl import load_workbook
for i in LisOfFiles:
xl = load_workbook(ListOfFiles[i], read_only=True)
However I get a TypeError: list indices must be integers or slices, not str
How can I solve this?但是我得到一个
TypeError: list indices must be integers or slices, not str
我该如何解决这个问题?
Try printing i in the for loop print(i)
.尝试在 for 循环
print(i)
中打印 i 。 Basically you are trying to access an element of a list with a string.基本上,您正在尝试使用字符串访问列表的元素。 In the first iteration this means
在第一次迭代中,这意味着
i = 'filename1.xlsm'
which translates to i = 'filename1.xlsm'
转换为LisOfFiles['filename1.xlsm']
However you can only access the elements of a list with a number ie LisOfFiles[0]
works fine.但是,您只能使用数字访问列表的元素,即
LisOfFiles[0]
可以正常工作。
The solution is to directly use i as input to load_workbook.解决方法是直接使用 i 作为 load_workbook 的输入。 However be aware that in every iteration of the loop xl gets overwritten
但是请注意,在循环的每次迭代中 xl 都会被覆盖
for i in LisOfFiles:
xl = load_workbook(i, read_only= True)
You are already iterating over the list.您已经在迭代列表。 No need to index it again:
无需再次索引它:
from openpyxl import load_workbook
for path in ListOfFiles:
xl = load_workbook(path, read_only=True)
Edit编辑
Note that in the code above, xl
gets re-assigned every time.请注意,在上面的代码中,每次都会重新分配
xl
。 This is probably not what you want.这可能不是你想要的。
You could capture the workbooks in a list:您可以在列表中捕获工作簿:
from openpyxl import load_workbook
workbooks = []
for path in ListOfFiles:
workbooks.append(load_workbook(path, read_only=True))
This can be shortened by using a list comprehension :这可以通过使用列表推导来缩短:
workbooks = [
load_workbook(path, read_only=True)
for path in ListOfFiles
]
If you want to be able to address them by filename, use a dict comprehension :如果您希望能够通过文件名来解决它们,请使用dict comprehension :
workbooks = {
path: load_workbook(path, read_only=True)
for path in ListOfFiles
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.