【问题标题】:Why am I getting an attribute error?为什么我会收到属性错误?
【发布时间】:2012-12-13 16:04:20
【问题描述】:

方法self.prepSetFile()返回的数据是字典类型

    dataTodump=self.prepSetFile()
    try:
        settingFile=os.path.join(self.settingsDir,"setting.txt")
        output_phil=open(settingFile,'w')
        pickle.dump(dataTodump,settingFile,0)
    except: raise

我不知道为什么会出现属性错误

属性错误:
“str”对象没有“write”属性

我什至测试了dataTodump的数据类型,显然是dict

【问题讨论】:

  • 始终在报告 Python 异常时包含 full 回溯。
  • except: raise,那你为什么还需要try-catch

标签: python dictionary pickle


【解决方案1】:

你需要传入一个open文件给pickle.dump;您只传入一个文件名:

output_phil=open(settingFile,'wb')
pickle.dump(dataTodump, output_phil, 0)

请注意,该文件以 二进制 模式打开,以防止在非 UNIX 平台上转换 \n 字节。

【讨论】:

  • 或更好:pickle.dump(dataTodump, output_phil, 0)
  • @glglgl:几乎;现在添加了wb 二进制模式。
猜你喜欢
  • 1970-01-01
  • 2020-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-05
  • 2018-06-22
  • 2020-01-12
  • 2016-01-01
相关资源
最近更新 更多