Skip to content
Advertisement

Cannot load a JSON file I just created (json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0))

I’m trying to work with json files, but I’m unable to load the file I just saved.

JavaScript

I’m not sure what I’m doing wrong. I tried json.loads(f.read().decode('UTF-8')) and json.load(f) and they both give me errors as well.

Edit: The purpose of this code is to store time spent on something as a json, and if the time exceeds a certain amount add something else (that’s why I’m trying to load the file, to attempt to get the int values stored)

Traceback when using json.load(f):

JavaScript

Advertisement

Answer

When you open a file “a+” (append plus read), the file pointer is set at the end of file, ready for the next write to append data. when you read, its already at EOF so you get the empty string "". Its the same as if you had witten

JavaScript

Its hard to manage a file for writing and reading, especially with python where an intermediate encoder/decoder for bytes to str translation may be caching data. There are other details to consider such as flushing data to make sure its really available for a read.

Better to segment your code to reading bits and writing bits, and close the file in between. To get the same sequence you’ve shown, you could

JavaScript

Running multiple times I get

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement