I believe you could simply do:

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({}))
Answer from Lucas Infante on Stack Overflow
🌐
Real Python
realpython.com › python-json
Working With JSON Data in Python – Real Python
August 20, 2025 - With pretty_frieda.json as the value of the outfile option, you write the output into the JSON file instead of showing the content in the terminal. If the file doesn’t exist yet, then Python creates the file on the way. If the target file already exists, then you overwrite the file with the new content. Note: You can prettify a JSON file in place by using the same file as infile and outfile arguments.
🌐
YouTube
youtube.com › pygpt
python create json file if not exists - YouTube
Instantly Download or Run the code at https://codegive.com creating a json file in python is a common task, and ensuring that the file exists before attempt...
Published   February 20, 2024
Views   86
🌐
Finxter
blog.finxter.com › home › learn python blog › python create json file
Python Create JSON File - Be on the Right Side of Change
November 2, 2022 - This function checks the current directory for the existence of the employees.json file · The first time this code runs, and this file is not found (isFile is False), an empty file is created and placed into the current working directory. 💡Note: The pass statement is a placeholder code and does nothing when executed. This is used here so a file is created, and nothing else occurs. If this code is rerun or the file exists, the following message is output to the terminal.
🌐
GeeksforGeeks
geeksforgeeks.org › python › create-a-file-if-not-exists-in-python
Create A File If Not Exists In Python - GeeksforGeeks
July 23, 2025 - In Python, creating a file if it does not exist is a common task that can be achieved with simplicity and efficiency. By employing the open() function with the 'x' mode, one can ensure that the file is created only if it does not already exist.
🌐
Better Stack
betterstack.com › community › questions › how-to-write-json-data-to-file-in-python
How do I write JSON data to a file in Python? | Better Stack Community
The with open statement opens the file "data.json" in "w" mode, which means it will be opened for writing. The file will be created if it does not exist, and truncated if it does exist.
🌐
TutsWiki
tutswiki.com › read-write-json-config-file-in-python
Writing and Reading JSON config file in Python :: TutsWiki Beta
import json article_info = { "domain" ... "w") as jsonfile: jsonfile.write(myJSON) print("Write successful") ... Note: “w” mode creates the file in the current working directory if it does not exists....
Find elsewhere
🌐
Python Forum
python-forum.io › thread-27694.html
empty json file error
I wrote this and since it creates an empty file it give me an error. with open('food.json', 'r+') as file: food = json.load(file)Error:Traceback (most recent call last): File 'c:/Users/User/MyStuff/mltipls.py', line 4, in foo...
🌐
GitHub
gist.github.com › keithweaver › b113801cd38a354b06a4ad59e3c14a7f
Check if file exists with Python · GitHub
Check if file exists with Python. GitHub Gist: instantly share code, notes, and snippets.
🌐
Replit
replit.com › home › discover › how to create a json file in python
How to create a JSON file in Python | Replit
The with open() statement manages the file. Using "w" for write mode is a key detail. It creates the file if it doesn't exist or completely overwrites it if it does, ensuring your JSON file always reflects the latest data.
🌐
Medium
medium.com › @ryan_forrester_ › writing-json-to-a-file-in-python-a-step-by-step-guide-630584957d07
Writing JSON to a File in Python: A Step-by-Step Guide | by ryan | Medium
November 6, 2024 - - `open(‘data.json’, ‘w’)`: This line opens a file named `data.json` in write mode (`’w’`). If the file does not exist, it will be created. - `with` statement: This ensures that the file is properly closed after its suite finishes, ...
🌐
LabEx
labex.io › tutorials › python-how-to-handle-missing-json-file-495790
How to handle missing JSON file | LabEx
from pathlib import Path def check_file_exists(file_path): return Path(file_path).is_file() ## Example usage json_file = '/home/labex/data.json' if check_file_exists(json_file): print("File exists") else: print("File not found")
Top answer
1 of 16
3349

data is a Python dictionary. It needs to be encoded as JSON before writing.

Use this for maximum compatibility (Python 2 and 3):

import json
with open('data.json', 'w') as f:
    json.dump(data, f)

On a modern system (i.e. Python 3 and UTF-8 support), you can write a nicer file using:

import json
with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=4)

See json documentation.

2 of 16
347

To get utf8-encoded file as opposed to ascii-encoded in the accepted answer for Python 2 use:

import io, json
with io.open('data.txt', 'w', encoding='utf-8') as f:
  f.write(json.dumps(data, ensure_ascii=False))

The code is simpler in Python 3:

import json
with open('data.txt', 'w') as f:
  json.dump(data, f, ensure_ascii=False)

On Windows, the encoding='utf-8' argument to open is still necessary.

To avoid storing an encoded copy of the data in memory (result of dumps) and to output utf8-encoded bytestrings in both Python 2 and 3, use:

import json, codecs
with open('data.txt', 'wb') as f:
    json.dump(data, codecs.getwriter('utf-8')(f), ensure_ascii=False)

The codecs.getwriter call is redundant in Python 3 but required for Python 2


Readability and size:

The use of ensure_ascii=False gives better readability and smaller size:

>>> json.dumps({'price': '€10'})
'{"price": "\\u20ac10"}'
>>> json.dumps({'price': '€10'}, ensure_ascii=False)
'{"price": "€10"}'

>>> len(json.dumps({'абвгд': 1}))
37
>>> len(json.dumps({'абвгд': 1}, ensure_ascii=False).encode('utf8'))
17

Further improve readability by adding flags indent=4, sort_keys=True (as suggested by dinos66) to arguments of dump or dumps. This way you'll get a nicely indented sorted structure in the json file at the cost of a slightly larger file size.

🌐
Stack Overflow
stackoverflow.com › questions › 36731221 › android-how-to-create-a-new-json-file-if-it-doesnt-exist-python
Android How to create a new json file if it doesn't exist python - Stack Overflow
thanks it helped but i used if not os.path.exists('hello.json'): with open('hello.json', 'wt') as inFile: inFile.write("") ... This question is in a collective: a subcommunity defined by tags with relevant content and experts. ... Is it better to redirect users who attempt to perform actions they can't yet... 7283 How do I check whether a file exists without exceptions?
🌐
Stack Overflow
stackoverflow.com › questions › 71233687 › create-new-file-with-other-name-if-file-name-already-exist-in-python
json - Create new file with other name if file name already exist in python - Stack Overflow
def writeContentToFile(mode, customername, workspacename, category, endpoint, jsonContent): path = os.path.join(os.getcwd(), customername, workspacename, category) Path(path).mkdir(parents=True, exist_ok=True) c = 1 while os.path.exists(path + "/" + (endpoint if c == 1 else endpoint + f'_{c}') + '.json'): c += 1 with open(path + "/" + (endpoint if c == 1 else endpoint + f'_{c}') + '.json', mode, encoding='utf-8') as f: json.dump(jsonContent, f, ensure_ascii=False, indent=4)
🌐
Quora
quora.com › How-do-I-write-JSON-in-Python
How to write JSON in Python - Quora
Answer (1 of 12): You can load a json file into a Python program by using json.load() - this makes a Python object which can then be manipulated easily that same as any other Python list, dictionary, or other value. You can then write a Python object out as JSON by using json.dump(). If you nee...