AttributeError:'tuple'对象没有属性'write'

dhc*_*dhc 6 python tuples attributeerror

我有一个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
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:

回溯(最近调用最后一次):文件"I:\ Cent 110\test.py",第19行,在openfile.write(item +'\n')中
AttributeError:'tuple'对象没有属性'write'

Mat*_*ias 10

你错过了开放.

openfile = open('test.txt','w')
Run Code Online (Sandbox Code Playgroud)

最后,当您尝试关闭文件时,会丢失一些parens

openfile.close()
Run Code Online (Sandbox Code Playgroud)

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

openfile.write(str(cost)+'\n')
Run Code Online (Sandbox Code Playgroud)

  • _open_不在您发布的代码中. (3认同)
  • @dhc:你*错过了开放.再看一下你的代码.这是微不足道的发现 - 解释告诉你什么行错误出现在所有你需要做的就是问自己,"什么是'openfile`,为什么没有它有一个'write`属性?".为此,请查看(密切!)您定义`openfile`的位置.你会发现你错过了公开声明. (2认同)