Reputation: 940
i have one class dumping a list containing strings into a .json file and another class loading this file. However i am getting weird errors that i dont understand - this is the content of the .json file (example):
["1", "1", "1", "1", "1", "1", "1", "11", "1", "1", "1.1.1.1", "11.11.11.11"]
This is the code that reads the .json file in another class:
with open('test.json','a+') as infile:
if os.stat('test.json').st_size != 0:
jsonimport = json.load(infile)
I was thinking that open() in Python does not create a file if it doesn't exist is related, but im not reading the file normally but instead using JSON to load the data...
This is the Error:
File "C:\Users\Administrator\Documents\QTTestGIT\IPv4calc.py", line 12, in __init__
self.CallPrompt()
File "C:\Users\Administrator\Documents\QTTestGIT\IPv4calc.py", line 18, in CallPrompt
jsonimport = json.load(infile)
File "C:\Program Files\Python36\lib\json\__init__.py", line 299, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "C:\Program Files\Python36\lib\json\__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "C:\Program Files\Python36\lib\json\decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Program Files\Python36\lib\json\decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Process finished with exit code 1
Upvotes: 0
Views: 2131
Reputation: 81604
It does not work because you are using the a+
mode to open the file.
json.load
uses the .read
method of the passed file-like object. Since you are using a+
mode, .read
will return an empty string (which makes sense as the cursor will be at the end of the file).
Change mode to r
(or don't provide any mode, r
is the default) and your code will work.
Alternatively, you can call infile.seek(0)
before calling json.load
but then I don't see the point of using a+
mode to begin with.
import json
file_name = 'test.json'
with open(file_name, 'a+') as infile:
if os.stat(file_name).st_size != 0:
infile.seek(0)
print(json.load(infile))
# ['1', '1', '1', '1', '1', '1', '1', '11', '1', '1', '1.1.1.1', '11.11.11.11']
Upvotes: 1