Python3“NoneType”在cs中读取耶稣诞生时

2024-04-26 19:04:38 发布

您现在位置:Python中文网/ 问答频道 /正文

使用本机python3.6和console加载CSV时出现问题,返回TypeError: 'NoneType'object is not iterable。你知道吗

CSV包含两列,分别是department\u 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'

Tags: andofcsvtheinfoiddataget
2条回答

在“get\u department\u entry”方法中

if len(data) == 3:

这将始终返回false,因为列数为2。因此,它将不返回任何值。你知道吗

这就是为什么你会犯这个错误。你知道吗

TypeError: 'NoneType' object is not iterable

你可以试试这个

while line:
    line = file_info.readline()
    print(line)
    department = get_department_entry(departments, line)
    if department:
        departments.update(department)

相关问题 更多 >