I'm trying to work with json files, but I'm unable to load the file I just saved.
time_vals = { "seconds": time_spent, "day": amnt}
json_o = json.dumps(time_vals, indent = 4)
with open(os.path.join(os.getcwd(), fname + ".json",), 'a+') as f:
loaded = json.loads(f.read()) <- error
f.write(json_o)
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):
Traceback (most recent call last):
File "C:\Users\julkt\PycharmProjects\pythonProject\venv\lib\site-packages\flask\app.py", line 2070, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\julkt\PycharmProjects\pythonProject\venv\lib\site-packages\flask\app.py", line 1515, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\julkt\PycharmProjects\pythonProject\venv\lib\site-packages\flask\app.py", line 1513, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\julkt\PycharmProjects\pythonProject\venv\lib\site-packages\flask\app.py", line 1499, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "C:/Users/julkt/Documents/Python_projectaaaaaaaaaaaaas/GUI project/guiproject.py", line 346, in send_url
loaded = json.load(f)
File "C:\Users\julkt\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
File "C:\Users\julkt\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "C:\Users\julkt\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\julkt\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
192.168.1.162 - - [16/Sep/2021 18:01:25] "POST /send_url HTTP/1.1" 500 -
a+puts the file pointer at the end of file. If you try to read, you get nothing because you are already EOF. Rarely is "a+" the right thing in python. You'd have to reposition the file pointer to get the read to do anything useful, but the only valid thing is toseek(0)otherwise you mess up the intermediate bytes to str decoder.loaded = json.load(f). But it wouldn't work because read is already at EOF.