2017-08-31 82 views
1

我得到试图读取一个JSON文件时出错:String对象有没有属性读取

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' 

这是错误:

 
      if os.path.exists(f) is True: 
---->   return json.loads(f.read()) 
      else: 
       return 'mocked.json' 

AttributeError: 'str' object has no attribute 'read' 

什么我做错了任何帮助将不胜感激。

+0

'”。加入()'导致串类型。所以你在一个字符串上执行'.read()' – Mangohero1

+1

'f' - 你的字符串是路径,你不能在字符串 – Vladyslav

回答

2

您的f只是一个字符串,不能读取字符串。我认为这里混淆的根源是os.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(...)可能会受到竞争条件。如果ifopen之间的文件被另一个进程删除,会发生什么情况?或者如果你没有权限打开它?

这可以通过try ING避免将其打开和处理,其中它是不可能的情况下:“

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 
     ... 
+0

上调用'read()'方法谢谢@MSeifert,赞赏 –