【问题标题】:Python AttributeError: 'str' object has no attribute 'read'Python AttributeError:'str'对象没有属性'read'
【发布时间】:2020-01-10 22:23:26
【问题描述】:

我目前尝试运行如下 Python 代码:

def from_file(filename, sep='\n'):
    "Parse a file into a list of strings, separated by sep."
    return (filename).read().strip().split(sep)

我得到如下错误: AttributeError: 'str' 对象没有属性 'read'

有什么想法吗?

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    Filename 只是文件的名称。您必须打开文件,才能创建文件对象。然后你就可以从这个文件对象中读取了。

    def from_file(filename, sep='\n'):
        """Parse a file into a list of strings, separated by sep"""
        with open(filename) as file:
            return file.read().strip().split(sep)
    

    【讨论】:

    • 我已尝试应用您的建议,但没有任何反应。非常感谢您的回复
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 2013-10-28
    • 1970-01-01
    • 2018-12-01
    • 2015-09-30
    • 2021-10-22
    相关资源
    最近更新 更多