类型错误:zip 参数 #1 必须支持函数迭代



我正在编写一个购物清单程序,用户可以选择是添加项目,编辑项目还是查看列表。我已经将它们全部设置为函数,以便用户可以输入必要的信息,程序调用该函数。所有项目都保存到 csv 文件中。

下面是添加项函数:

import csv
def AddItem(name,shop, qantity, priority_level,price,bought):
with open("C:\Users\sophie\Documents\Sophie\Homework\Year 11\Computer Science\ShoppingList.csv","a", newline = '') as csvfile:
fieldnames=['Name','Shop','Quantity','Price','Priority_Level','Bought']
writer=csv.DictWriter(csvfile,fieldnames==fieldnames)
writer.writeheader()
writer.writerow({'Name':name, 'Shop': shop, 'Quantity': quantity, 'Price':price,'Priority_Level':priority_level, 'Bought': bought})
print('You have now added ',name,' to your shopping list.')

以下是用户输入特定详细信息的代码:

ModeChose=='A':
name=input('Please enter the name of the item you want to add. ')
shop=input('Please enter the shop you will buy it from, if you don’t know, press zero. ')
int_quantity=input('Please enter the quantity of the item you will buy, if you don’t know, press zero. ')
int_priority_level=int(input('Please enter the priority level of the item you will buy, if you don’t know, press zero (1 is high priority, all the way to 5 which is low priority). '))
quantity=str(int_quantity)
priority_level=str(int_priority_level)
int_price=int(input('Please enter the price of the product roundest to the nearest pound, if you don’t know, press zero. '))
price=str(int_price)
bought=input('Please enter Y if you have bought the item and N is you haven’t. ')
AddItem(name, shop, quantity, priority_level, price, bought)

这是我运行它时遇到的错误:

Traceback (most recent call last):
File "C:UserssophieDocumentsSophieHomeworkYear 11Computer ScienceShoppingList.py", line 103, in <module>
AddItem(name, shop, quantity, priority_level, price, bought)
File "C:UserssophieDocumentsSophieHomeworkYear 11Computer ScienceShoppingList.py", line 8, in AddItem
writer.writeheader()
File "C:Python34libcsv.py", line 141, in writeheader
header = dict(zip(self.fieldnames, self.fieldnames))
TypeError: zip argument #1 must support iteration

一目了然,可能是这一行:

writer=csv.DictWriter(csvfile,fieldnames==fieldnames)

确保使用单个 = 而不是 ==。您的代码当前所做的是将 DictWriter 的第二个位置参数设置为True/False布尔值。您要做的是将关键字参数fieldnames设置为适当的对象。

最新更新