我是 python 新手,但我一直在尝试创建一个从 Excel 文件中读取(openpyxl)的字典列表。使用 iter_rows() 读取文件中的所有行,然后将每一行添加为字典。然后脚本将该字典附加到一个列表中,但是在查看字典列表时,它只显示最后一行(或字典)被附加了几次。我不确定为什么它只附加最后一行?
import openpyxl
# Give the location of the file
path = 'C:\\Users\\.....\\pythonExcelDemo.xlsx'
# workbook object is created
wb_obj = openpyxl.load_workbook(path)
thisList = []
inner_dict = {}
sheet_obj = wb_obj.active
for row in sheet_obj.iter_rows(2, 6, 1, 3):
for cell in row:
if cell.column == 1:
inner_dict.update({'Students Name': cell.value})
if cell.column == 2:
inner_dict.update({'Department': cell.value})
if cell.column == 3:
inner_dict.update({'Fund': cell.value})
thisList.append(inner_dict)
print(thisList)
Output-----
[{'Students Name': 'Keli', 'Department': 'Branch', 'Fund': 160}, {'Students Name': 'Keli', 'Department': 'Branch', 'Fund': 160}, {'Students Name': 'Keli', 'Department': 'Branch', 'Fund': 160}, {'Students Name': 'Keli', 'Department': 'Branch', 'Fund': 160}, {'Students Name': 'Keli', 'Department': 'Branch', 'Fund': 160}]