0

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
Flying Thunder
  • 890
  • 2
  • 11
  • 37
  • 1
    There is nothing wrong with your code as included in the question above. can you show what your json file actually contains? is it valid json? The error makes it sound like its an issue with the file and that it might not actually be valid json. On another note 'a+' mode works fine for me... – Craicerjack Oct 04 '18 at 10:28
  • If i use `r` i get an error that the file doesnt exist because the file gets generated at an earlier point but for some reason it still complains... i think i have to use `lambda` so that the `json.load` is not executed one start but only when i call it? – Flying Thunder Oct 04 '18 at 10:36
  • Surprised to find mode 'a+' works for reading. I don't like it though, would think that also involves append permission. Why risk changing files' contents? This is in python 2.7.15 – Paul Oct 04 '18 at 10:38
  • 1
    @Paul The `+` in `a+` stands for "open a disk file for updating (reading and writing)", so it makes sense that `a+` provides `.read` – DeepSpace Oct 04 '18 at 10:39

1 Answers1

1

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']
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
  • As said in another comment, i cant use `r` for some reason, because then it complains that the file doesnt exists, although at the point where this piece of code is executed, the file is generated by another part... Theres a way to prevent execution of code when initiating it but i dont know – Flying Thunder Oct 04 '18 at 10:39
  • 1
    @FlyingThunder "Another part" of what? your program? if so I'd check why that other part does not actually create the file, or add error-handling in case the file does not exist. Anyway, see the updated part of my answer about using `seek` – DeepSpace Oct 04 '18 at 10:41
  • It can't be the first sentence "It does not work because you are using the a+ mode to open the file." because it works fine here in 'a+' mode. Something else must be different. One thing that is different, is I am running Linux (Ubuntu 18.04) whereas the OP is on Windows. – Paul Oct 04 '18 at 10:41
  • 2
    @FlyingThunder " i cant use r for some reason, because then it complains that the file doesnt exists" => and ??? Just catch the exception and you're done. Seriously, opening in a+ mode and testing the stats when all you want is to read the file is a complete WTF. – bruno desthuilliers Oct 04 '18 at 10:44
  • Yes, i just added try, but i wanted to know why it doesnt work, i didnt knew a+ puts the cursor on the end – Flying Thunder Oct 04 '18 at 10:45