我有一个文件,目前保存为 csv,但它最初是一个 Excel 文件 (Excel 2010)。
它的内容是这样的:
Name;Category;Address
McFood;Fast Food;Street 1
BurgerEmperor;Fast Food;Way 1
BlueFrenchHorn;French;Street 12
PetesPizza;Italian;whatever
SubZero;Fast Food;Highway 6
我将其保存为 csv 以便能够解析它。目前我使用 DictReader ( here is the code and a corresponding question )
是否有像 xlrd 这样的 Excel 模块可用的类似 DictReader 的东西? 我将如何更改我的代码?
最佳答案
将此作为答案发布,可能会帮助那些寻找类似解决方案的人。 github(不是我的)上有一个包含潜在解决方案的要点。可能需要一些调整以适用于您的特定情况:Github Gist
对于那些不想点击的人,这是代码:
try:
import xlrd
import mmap
def XLSDictReader(f, sheet_index=0):
data = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
book = xlrd.open_workbook(file_contents=data)
sheet = book.sheet_by_index(sheet_index)
def item(i, j):
return (sheet.cell_value(0,j), sheet.cell_value(i,j))
return ( dict(item(i,j) for j in range(sheet.ncols)) \
for i in range(1, sheet.nrows) )
except ImportError:
XLSDictReader = None
关于python - 用于 Excel 文件的 DictReader,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25894917/