我正在尝试使用XLWT从CSV文件(将邮政编码压缩为State)写入Excel文件,但是当我打开csv并从那里获取statename时出现此错误,否则,如果我设置了一些硬编码值,则该代码正在执行。
import xlwt
import csv
row = 1
excelFile = xlwt.Workbook(encoding='utf-8')
sheet1 = excelFile.add_sheet('SampleData')
sheet1.col(0).width = 5000
sheet1.col(1).width = 5000
sheet1.write(0, 0, "Zip")
sheet1.write(0, 1, "State")
zip = '43215'
with open("usZipToCity.csv", 'r', encoding='utf-8') as csvFile:
reader = csv.reader(csvFile)
for row in reader:
if row:
if zip in row:
stateName = row[1]
sheet1.write(row, 0, zip)
sheet1.write(row, 1, stateName)
row += 1
excelFile.save("SampleData.xls")
错误回溯:
Traceback (most recent call last):
File "G:/scrapingtasks/toddkreal_property/Tester.py", line 47, in <module>
sheet1.write(row, 0, zip)
File "C:\Users\muhammadhamaadlatif\AppData\Local\Programs\Python\Python37-32\lib\site-packages\xlwt\Worksheet.py", line 1088, in write
self.row(r).write(c, label, style)
File "C:\Users\muhammadhamaadlatif\AppData\Local\Programs\Python\Python37-32\lib\site-packages\xlwt\Worksheet.py", line 1139, in row
if indx not in self.__rows:
TypeError: unhashable type: 'list'
答案 0 :(得分:0)
正如Martijn所指出的,您将row
用于两个不同的目的:
解决此问题的最快方法是为每种目的使用不同的变量名。例如,您可以在提供的代码的第13、14、15和16行中将row
重命名为csvrow
。
如果您有更多时间,建议您看一下以下代码。它包括一些对初始实现的样式修复,以及一个您可能会感兴趣的write_row()
函数。
import xwlt
import csv
from itertools import count
if __name__ == "__main__":
# Create an Excel file
EXCELFILE = xwlt.WorkBook(encoding="utf-8")
# Setup a sheet
SHEET = EXCELFILE.add_sheet('SampleData')
SHEET.col(0).width = 5000
SHEET.col(1).width = 5000
# Define an easy way to write a row of data to SHEET
ROW_IDX = count()
def write_row(*args):
"""Writes a row of data into SHEET"""
row_idx = next(ROW_IDX)
for col_idx, arg in enumerate(args):
SHEET.write(row_idx, col_idx, arg)
# Write the header (first row)
write_row("Zip", "State")
# Set ZIP to the zip code we are interested in
ZIP = '43215'
# Parse the csv file
with open("usZipToCity.csv", encoding="utf-8") as CSVFILE:
for CSVROW in csv.reader(CSVFILE):
if ZIP in CSVROW:
# CSVROW[1] contains a state name
write_row(ZIP, CSVROW[1])
# Write the Excel file to disk
EXCEFILE.save("SampleData.xls")
注意:从您的代码来看,我不清楚您是否希望在csv文件中找到多个匹配的行。如果没有,您可能应该在第一场比赛后使用break
。