0

I have a file that is updated with new content and saved every hour:

with open('data.txt','w') as outfile:
    json.dump(data,outfile)

I then read this file at any given time:

with open('data.txt') as json_file:
    data = json.load(json_file)

The problem I'm having is sometimes this file is in the process of being updated with new content when trying to read the file which results in a json.decoder.JSONDecodeError. How can I avoid this error? Maybe a try except case that waits for the file to be readable?

wormyworm
  • 179
  • 8

1 Answers1

1

Easiest way, would be to catch JSONDecodeError.

try:
    with open('data.txt') as json_file:
        data = json.load(json_file)
except JSONDecodeError:
    time.sleep(10)
    with open('data.txt') as json_file:
        data = json.load(json_file)

Or you can try answer from https://stackoverflow.com/a/11115521/4916849.

Alex Bodnya
  • 120
  • 10