2016-07-15 48 views
0

我有...文件打開失敗時,W +參數一起使用

datadir = os.path.dirname(__file__) + '/../some/place' 
session_file = '/user_session.json' 

with open(datadir + session_file, 'r') as data_file:  
    data = json.load(data_file) 
    print data 

而這按預期工作。我可以在我的json文件中加載json並訪問它。

我想使用w+參數,這樣如果文件不存在,它會被創建(儘管空白)。

除了當我使用w+加載失敗,下面的錯誤和文件被覆蓋一個空白。

ValueError('No JSON object could be decoded',) 

如何創建文件,如果它不存在,但如果它是讀取它,沒有失敗像這樣?

+0

我不知道創建一個空文件對你有多大用處。 'json.load'會在嘗試解析空文件時引發異常,所以也許你應該抓住'FileNotFoundError'(或者Python 2中的'IOError'),然後做適當的操作。 – Blckknght

+0

是的,我認爲這是發生了什麼事。也許我應該寫一些空字典作爲json來初始化文件? –

+0

問題是,空白文件會覆蓋好文件,即使其中存在有效的json。 –

回答

0

您要檢查文件是否存在,並作出相應的反應:

import json 
import os.path 

datadir = os.path.dirname(__file__) 
session_file = 'user_session.json' 
path = os.path.join(datadir, '..', 'some', 'place', session_file) 

# If the file exists, read the data. 
if os.path.exists(path): 
    with open(path, 'r') as f: 
     data = json.load(f) 
     print data 
else: 
    with open(path, 'w+') as f: 
     # Initialize the session file as you see fit. 
     # you can't use json.load(f) here as the file was just created, 
     # and so it would not decode into JSON, thus raising the same error 
     # you are running into. 

注意使用os.path.join這裏;這是構建文件路徑而不是連接字符串的更好方法。實質上,使用os.path.join可確保文件路徑仍將包含有效的斜槓,而不管您的操作系統如何。

+0

好的提示路徑加入:) –

+0

雖然我仍然不明白爲什麼''w +''最終會覆蓋在我的原始示例中的有效文件中。 –

+1

'w'表示'打開文件進行寫入,刪除任何現有內容'。 '+'的意思是'也允許閱讀'。如果您想打開文件進行讀/寫_並保留contents_,請使用'a +'。 –

0

嘗試測試是否該文件是存在的

import os.path 
import os 
datadir = os.path.dirname(__file__) + '/../some/place' 
session_file = '/user_session.json' 

path = datadir + session_file 
if os.path.exists(path): 
    open(path, 'w+').close() 

with open(path , 'r') as data_file:  
    data = json.load(data_file) 
    print data 
+0

該文件在那裏,因爲它加載了''r''。但我喜歡你的方法:) –

+0

這不會解決這個問題 - 當你用'w +'的值調用'json.load'時,讀取會失敗。 –

+0

@RushyPanchal同意,修復 – galaxyan