2017-08-25 56 views
0

我正在編碼購物清單程序,用戶可以選擇是否添加項目,編輯項目或查看列表。我已經完成了所有功能,用戶可以輸入必要的信息,程序調用該功能。所有的項目都被保存到一個CSV文件。TypeError:zip參數#1必須支持迭代功能

這裏是的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 
+4

'fieldnames = fieldnames'。只有一個'='不是兩個。 –

+0

謝謝,它的作品 –

回答

1

一眼就可以看到這一行:

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

確保使用single = not ==。您的代碼當前所做的是將DictWriter的第二個位置參數設置爲一個True/False布爾值。你想要做的是將關鍵字參數fieldnames設置爲適當的對象。

+1

好抓。所以'fieldnames'可能被接受,但是作爲_boolean_。所以錯字問題,但不是微不足道的。所以+1 –

+0

故事的道德:早期失敗。我認爲'csv'模塊中的一個錯誤是'DictWriter'在實際嘗試將該值用作'zip'的參數之前沒有捕獲這個錯誤。 – chepner

+0

@chepner csv模塊可以修改爲在第一個模塊之後不接受位置參數,是的... –

相關問題