【问题标题】:String object has no attribute read字符串对象没有读取属性
【发布时间】:2017-08-31 13:20:09
【问题描述】:

我在尝试读取 JSON 文件时遇到错误:

def get_mocked_json(self, filename):
    f = os.path.join(os.path.dirname(os.path.realpath(__file__)), '../fixtures', filename)
    if os.path.exists(f) is True:
        return json.loads(f.read())
    else:
        return 'mocked.json'

这是错误:

如果 os.path.exists(f) 为真: ----> 返回 json.loads(f.read()) 别的: 返回“嘲笑.json” AttributeError:“str”对象没有属性“read”

对我做错的任何帮助将不胜感激。

【问题讨论】:

  • ' '.join() 产生字符串类型。所以你在一个字符串上执行.read()
  • f - 是你的带路径的字符串,你不能在字符串上调用read() 方法

标签: python string file


【解决方案1】:

您的f 只是一个字符串,无法读取字符串。我认为这里造成混淆的原因是 os.path 函数只是确保 string 代表操作系统上的有效文件-path。

要真正read 它,你需要先open 文件。这将返回一个可以是 read 的流:

def get_mocked_json(self, filename):
    f = os.path.join(os.path.dirname(os.path.realpath(__file__)), '../fixtures', filename)
    if os.path.exists(f) is True:
        with open(f) as fin:  # this is new
            return json.loads(fin.read())
    else:
        ...

请注意,if os.path.exists(...) 可能会受到竞争条件的影响。如果在if 和open 之间文件被另一个进程删除会发生什么?或者,如果您没有权限打开它?

trying 打开它并处理不可能的情况可以避免这种情况:

def get_mocked_json(self, filename):
    f = os.path.join(os.path.dirname(os.path.realpath(__file__)), '../fixtures', filename)
    try:
        with open(f) as fin:
            return json.loads(fin.read())
    except Exception:  # or IOError
        ...

【讨论】:

  • 非常感谢@MSeifert,非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-26
  • 1970-01-01
  • 2011-08-09
  • 2017-10-23
  • 2020-06-26
  • 1970-01-01
相关资源
最近更新 更多