我有一個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'
你應該檢查出[''with''聲明】(http://docs.python.org/reference/compound_stmts.html#the-with-statement)打開文件 - 這意味着你不不必手動關閉它們,即使在例外情況下也能正常工作。 – 2012-04-17 10:53:23
@Lattyware:我一定會檢查一下。感謝您的意見。 – dhc 2012-04-17 11:00:43