【问题标题】:.read() returns "unicode object has no attribute read" in python with askopenfilename().read() 在 python 中使用 askopenfilename() 返回“unicode object has no attribute read”
【发布时间】:2018-01-31 11:03:17
【问题描述】:

我正在尝试在 Python 的 Tkinter 中为 scrolledText 创建一个导入函数,但是在读取文件时,会引发 AttributeError。代码:

def open_command():
    openfile = tkFileDialog.askopenfilename()
    if openfile != None:
        contents = openfile.read()
        textPad.delete('1.0', END)
        textPad.insert('1.0', contents)
        openfile.close()

错误:

    contents = openfile.read()
AttributeError: 'unicode' object has no attribute 'read'

我想澄清一下'textPad' 指的是一个'ScrolledText' 对象。 有谁知道为什么会这样?起初我以为错误可能来自编码,所以我用 UTF-8 编码,但它仍然返回相同的错误。提前致谢!

【问题讨论】:

  • askopenfilename 在文件名上返回一个文件 _name. You can't call read()`,这正是错误告诉你的内容。

标签: python unicode tkinter attributeerror


【解决方案1】:

tkFileDialog.askopenfilename() 返回文件名而不是文件对象。您需要执行以下操作:

def open_command():  
    filename = tkFileDialog.askopenfilename()
    if filename is not None:
        with open(filename) as f:
           contents = f.read()
        textPad.delete('1.0', END)
        textPad.insert('1.0', contents)

[如果您使用的是 Python 2.7,请考虑使用 Python 3 或将以上内容更改为 open(filename, 'r')]

【讨论】:

  • 非常感谢!切换到 Python 3 是否有特定原因?我更习惯 Python 2.7。
  • 2020 年之后将不再维护 Python 2.7。Python 3 有很多有用的功能,更新的模块将不支持 2.7。如果您对字符串/ unicode 做了任何事情,那么切换将是彻底的解脱。 pythonclock.org
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-24
  • 1970-01-01
  • 2023-03-16
相关资源
最近更新 更多