2012-04-17 153 views
5

我有一個Python類的家庭作業分配,並且遇到了一個我不明白的錯誤。在Windows上運行的Python IDLE V3.2.2 7.AttributeError:'元組'對象沒有屬性'寫'

下面是問題發生的事情:

#local variables 
number=0 
item='' 
cost='' 

#prompt user how many entries 
number=int(input('\nHow many items to add?: ')) 

#open file 
openfile=('test.txt','w') 

#starts for loop to write new lines 
for count in range(1,number+1): 
    print('\nFor item #',count,'.',sep='') 
    item=input('Name: ') 
    cost=float(input('Cost: $')) 

    #write to file 
    openfile.write(item+'\n') 
    openfile.write(cost+'\n') 

#Display message and closes file 
print('Records written to test.txt.',sep='') 
openfile.close 

這是我得到的錯誤:

Traceback (most recent call last): File "I:\Cent 110\test.py", line 19, in openfile.write(item+'\n')
AttributeError: 'tuple' object has no attribute 'write'

+2

你應該檢查出[''with''聲明】(http://docs.python.org/reference/compound_stmts.html#the-with-statement)打開文件 - 這意味着你不不必手動關閉它們,即使在例外情況下也能正常工作。 – 2012-04-17 10:53:23

+0

@Lattyware:我一定會檢查一下。感謝您的意見。 – dhc 2012-04-17 11:00:43

回答

7

你錯過了open

openfile = open('test.txt','w') 

,並在年底有遺漏括號,當您試圖關閉文件

openfile.close() 

編輯:我剛纔看到的另一個問題。

openfile.write(str(cost)+'\n') 
+0

openfile = open('test.txt','w')在那裏。感謝tho :) – dhc 2012-04-17 10:50:08

+3

_open_不在您發佈的代碼中。 – Matthias 2012-04-17 10:51:36

+0

感謝您捕捉結束括號。完全錯過了它。但是,這並沒有解決我的問題。 :( – dhc 2012-04-17 10:52:56

相關問題