1

I'm trying to create a simple function which I can use to store json data to a file. I currently have this code

def data_store(key_id, key_info):
    try:
        with open('data.txt', 'a') as f:
            data = json.load(f)
            data[key_id] = key_info
            json.dump(data, f)
        pass
    except Exception:
        print("Error in data store")

The idea is the load what data is currently within the text file, then create or edit the json data. So running the code...

data_store("foo","bar")

The function will then read what's within the text file, then allow me to append the json data with either replacing what's there (if "foo" exists) or create it if it doesn't exist

This has been throwing errors at me however, Any ideas?

1 Answers1

4

a mode would not work for both reading and writing at the same time. Instead, use r+:

with open('data.txt', 'r+') as f:
    data = json.load(f)
    data[key_id] = key_info
    f.seek(0)
    json.dump(data, f)
    f.truncate()

seek(0) call here moves the cursor back to the beginning of the file. truncate() helps in situations where the new file contents is less than the old one.

And, as a side note, try to avoid having a bare except clause, or/and log the error and the traceback properly.

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195