【问题标题】:AttributeError: 'tuple' object has no attribute 'write'AttributeError:“元组”对象没有“写入”属性
【发布时间】:2012-04-28 16:53:15
【问题描述】:

我有一个 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' 对象没有属性 'write'

【问题讨论】:

  • 您应该查看with statement 打开文件 - 这意味着您不必手动关闭它们,即使在异常情况下也能正常工作。

标签: python tuples attributeerror


【解决方案1】:

你错过了open

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

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

openfile.close()

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

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

【讨论】:

  • openfile=open('test.txt','w') 在那里。谢谢你:)
  • 感谢您抓住结尾括号。完全错过了。但是,这并没有解决我的问题。 :(
  • @dhc:你错过了开放。再看看你的代码。这很容易发现 - 解释器会告诉您错误出现在哪一行。您所要做的就是问自己“openfile 是什么,为什么它没有write 属性?”。为此,请查看(仔细!)定义openfile 的位置。你会发现你错过了 open 语句。
猜你喜欢
  • 2021-03-20
  • 2013-03-01
  • 2013-06-21
  • 2017-11-27
  • 2021-07-30
  • 2013-07-29
  • 2020-08-29
  • 2015-04-22
相关资源
最近更新 更多