2015-10-07 65 views
0

我目前正在制作一个需要JSON数据库文件的程序。我希望程序检查文件,如果它存在,那么它是完美的,运行程序的其余部分,但是如果它不存在,请在文件内创建'Accounts.json'与{},而不是运行该程序。Python:检查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") 

回答

2

我相信你可以简单地做:

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({})) 
+1

为什么你正在使用'这里codecs'? – styvane

+0

@Styvane 我编辑了使用'io'(它也接受'encoding'参数,如果需要的话)的答案,因为它可以在python2和python3中使用。感谢您指出。 – maccinza

相关问题