6

我有一个 Python 课程的家庭作业,并且遇到了一个我不理解的错误。在 Windows 7 上运行 Python IDLE v3.2.2。

下面是问题发生的地方:

#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

这是我得到的错误:

回溯(最后一次调用):文件“I:\Cent 110\test.py”,第 19 行,在 openfile.write(item+'\n')
AttributeError: 'tuple' object has no attribute 'write'

4

1 回答 1

12

你错过了open

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

最后,当您尝试关闭文件时,缺少括号

openfile.close()

编辑:我刚刚看到另一个问题。

openfile.write(str(cost)+'\n')
于 2012-04-17T10:47:42.470 回答