0

I'm using two JSON files, one for storing and loading device variables and another one for mqtt infos. I'm using a load_config function to load the correct file and then load it as JSON. When the file exists, it works without any problem, but when the file is not existing, it throws a file not found error, obviously. but My function contains an exception block to handle this by creating the file, but it isn't called. Here's my code for the function:

def load_config(config_path):
    with open(config_path) as f:  #Config
        try:
            return json.load(f)
        except OSError:
            print("file not there, creating it")
            open(config_path, "w")
        except json.JSONDecodeError:
            return {}
    
    f.close()

I call that function like this:

DEVICE_PATH = 'config.json'
MQTT_PATH = 'mqtt.json'


conf = load_config(DEVICE_PATH)  #load device config
mqtt_conf = load_config(MQTT_PATH) #load mqtt config
mqtt_broker_ip = mqtt_conf['ip']  #setup mqtt
mqtt_broker_port = mqtt_conf['port']
mqtt_user = mqtt_conf['username']
mqtt_pass = mqtt_conf['password']
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set(mqtt_user, password=mqtt_pass)
client.connect(mqtt_broker_ip, mqtt_broker_port, keepalive = 60, bind_address="" )

what am I doing wrong? When I open the file directly with the load_config via with open(config_path, "a") as f: everything in it gets deleted, with x it just throws an exception if the file exists and with w, it gets also overwritten.

unrealapex
  • 578
  • 9
  • 23
tenn0
  • 3
  • 3
  • 2
    `if os.path.isfile(config_path):` – Lei Yang Jun 29 '21 at 01:09
  • I thought, if I handle the Json exception, why shouldn't I handle this exception also here? – tenn0 Jun 29 '21 at 01:26
  • Does this answer your question? [How to have Python check if a file exists and create it if it doesn't?](https://stackoverflow.com/questions/14990907/how-to-have-python-check-if-a-file-exists-and-create-it-if-it-doesnt) – ThePyGuy Jun 29 '21 at 01:55
  • I had a logic error. I wanted to handle the IO error when the file was already opened and the json was parsed. I went with the approach of @LeiYang, checking if the file existed – tenn0 Jun 29 '21 at 06:24
  • @EdKloczko you may want to read on [EAFP vs LBYL](https://betterprogramming.pub/in-python-dont-look-before-you-leap-cff250881930). – bereal Jun 29 '21 at 07:35
  • 1
    Why create a new empty file if you're not going to write into it anyway? – bereal Jun 29 '21 at 07:41
  • im not writing to it yet. Later it saves a device config to this file with another function – tenn0 Jun 29 '21 at 12:37

2 Answers2

0

What you are trying to accomplish is already an open() built-in functionality.

Just skip the whole file existence check and load the JSON in w+ mode:

with open("file.json", "w+") as f:
    try:
        data =  json.load(f)
    except JSONDecodeError:
        data = {}

w+ opens any file in read and write mode and creates the filename if it doesn't exist.

Keep in mind that dumping any data with this mode will entirely overwrite any existing file's content.

Just as a side note, you might need to explore some basic knowledge about file processing, to avoid being stuck with a similar issue very soon.

0

Since I had a logic error, the exception IOError would never been raised. I opened the file and tried to load into json. Now I just check beforehands, if the file not exists, and create it.

def load_config(config_path):
    if not os.path.isfile(config_path):
        open(config_path, "w+")
    with open(config_path) as f:  #Config
        try:
            return json.load(f)
        except json.JSONDecodeError:
            return {} 
tenn0
  • 3
  • 3