使用W +参数时文件打开失败

时间:2016-07-15 03:39:14

标签: python

我有......

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',)

如果文件不在那里我怎么能创建文件,如果是,那就读它,不会出现这样的错误?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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可确保文件路径仍包含有效的斜杠,无论您的操作系统如何。