2017-08-31 88 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,讚賞 –