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
  • Can you provide us your data.txt file or at least some data from it ? Commented Apr 22, 2016 at 12:07

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.