我正在编写购物清单程序,用户可以选择是添加项目,编辑项目还是查看列表。我已经使它们具有所有功能,因此用户可以输入必要的信息,程序调用该功能。所有项目都保存到csv文件中。
这是AddItem函数:
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:\Users\sophie\Documents\Sophie\Homework\Year 11\Computer Science\ShoppingList.py", line 103, in <module>
AddItem(name, shop, quantity, priority_level, price, bought)
File "C:\Users\sophie\Documents\Sophie\Homework\Year 11\Computer Science\ShoppingList.py", line 8, in AddItem
writer.writeheader()
File "C:\Python34\lib\csv.py", line 141, in writeheader
header = dict(zip(self.fieldnames, self.fieldnames))
TypeError: zip argument #1 must support iteration
答案 0 :(得分:2)
一眼就可以看出这一行:
writer=csv.DictWriter(csvfile,fieldnames==fieldnames)
确保使用单个=不==。您的代码当前所做的是将DictWriter的第二个位置参数设置为True
/ False
布尔值。您要做的是将关键字参数fieldnames
设置为适当的对象。