Python:检查 JSON 文件并在需要时创建一个

Csa*_*arg 6 python

我目前正在制作一个需要 JSON 数据库文件的程序。我希望程序检查文件,如果它在那里,那么它就完美了,运行程序的其余部分,但如果它不存在{},则在文件内部创建“Accounts.json” ,而不是运行程序。

我该怎么做?什么是最有效的方法。

注意:我用它来检查,但我将如何创建文件:

def startupCheck():
    if os.path.isfile(PATH) and os.access(PATH, os.R_OK):
        # checks if file exists
        print ("File exists and is readable")
    else:
        print ("Either file is missing or is not readable")
Run Code Online (Sandbox Code Playgroud)

Luc*_*nte 5

我相信你可以简单地做:

import io
import json
import os

def startupCheck():
    if os.path.isfile(PATH) and os.access(PATH, os.R_OK):
        # checks if file exists
        print ("File exists and is readable")
    else:
        print ("Either file is missing or is not readable, creating file...")
        with io.open(os.path.join(PATH, 'Accounts.json'), 'w') as db_file:
            db_file.write(json.dumps({}))
Run Code Online (Sandbox Code Playgroud)


Mis*_*isa 5

我就是这样做的。我希望它有帮助。编辑,是的,它现在看起来像一个代码:D

import json
import os

def where_json(file_name):
    return os.path.exists(file_name)


if where_json('data.json'):
    pass

else:

    data = {  
        'user': input('User input: '),
        'pass': input('Pass input: ')
    }


    with open('data.json', 'w') as outfile:  
        json.dump(data, outfile)
Run Code Online (Sandbox Code Playgroud)