下面是我的代码:
import json, xlrd
import datetime as dt
# This is the Excel data (no keys)
filename=r'C:\Users\timhe\OneDrive\Desktop\people_from_excel.json'
# Open the file (standard file open stuff)
with open(filename, 'r', encoding='utf-8-sig', newline='') as f:
# Load the whole json file into an object named people
people=json.load(f)
print(people)
# Dictionaries are in a list, loop through and display each dictionary.
for p in people:
name=p['Full Name']
byear=p['Birth Year']
# Excel date pretty tricky, use xlrd module.
y, m, d, h, i, s=xlrd.xldate_as_tuple(p['Date Joined'], 0)
joined=dt.date(y, m, d)
balance='$'+f"{p['Balance']:,.2f}"
print(f"{name:<22} {byear} {joined:%m/%d/%Y} {balance:>12}")
我将一个Excel数据文件转换为JSON,当我运行代码时,我得到了这个错误:
TypeError: '<' not supported between instances of 'str' and 'float'
我猜某个地方的数据类型必须更改,但我不确定需要在哪里进行更改。
1条答案
按热度按时间o8x7eapl1#
出现这个错误可能是因为p字典中的“Birth Year”值是一个浮点数,而您试图将它与行name=p['Full Name ']中的字符串进行比较。
在比较中使用出生年份之前,需要将其转换为整数或字符串。
或