使用本机Python 3.6加载CSV时出现问题,并且控制台返回TypeError: 'NoneType'object is not iterable
。
CSV包含2列,分别是department_id(int)和department(string)。
由于这是类型错误,所以我希望这很简单,但是我睡眠不足,我只需要这样做即可。这是我在CSV中读取的代码。任何帮助将不胜感激,因为我认为这应该是一个简单的解决方法(也许)。
#write function to create dict of department and within each a dict of # of count of purchase and number of first orders
def get_department_entry(departments, line):
data = line.strip().split(',')
if len(data) == 2:
# create a dictionary entry
# allows us to reference the product info using product id
# we also create a "metrics" : { "request_count": "0", "number_of_first_orders" : "0" } which
# will hold our metric information
department_info = {"department_id": data[0], "departments": data[1]}
return departments.update({data[0] : department_info})
else:
return
#*****************************************
departments = {}
# go through the products and populate our data structure
with open("departments.csv", encoding = 'utf-8') as file_info:
# # skip the header
line = file_info.readline()
while line:
line = file_info.readline()
print(line)
departments = get_department_entry(departments, line)
for entry in departments:
# go through all the products and output the metrics
print(departments[entry]["department_id"], departments[entry]['department'])
#*******************************************************
跟踪
Traceback (most recent call last):
File "<ipython-input-24-aa6291de102a>", line 11, in <module>
departments = get_department_entry(departments, line)
File "<ipython-input-23-11dd6139f61e>", line 13, in get_department_entry
return departments.update({data[0] : department_info})
AttributeError: 'NoneType' object has no attribute 'update'
答案 0 :(得分:0)
在“ get_department_entry”方法中,您已编写
if len(data) == 3:
这将始终返回false,因为列数为2。因此,它将返回None。
这就是为什么您会收到此错误。
TypeError: 'NoneType' object is not iterable
答案 1 :(得分:0)
您可以尝试
while line:
line = file_info.readline()
print(line)
department = get_department_entry(departments, line)
if department:
departments.update(department)