Python-无法从JSON导入?

时间:2018-10-04 10:23:51

标签: python json file

我有一个类将包含字符串的列表转储到.json文件中,而另一个类则加载此文件。但是我收到了我不明白的怪异错误-这是.json文件的内容(示例): ["1", "1", "1", "1", "1", "1", "1", "11", "1", "1", "1.1.1.1", "11.11.11.11"]

这是读取另一个类中的.json文件的代码:

 with open('test.json','a+') as infile:
        if os.stat('test.json').st_size != 0:
            jsonimport = json.load(infile)

我以为open() in Python does not create a file if it doesn't exist是相关的,但是我不是正常读取文件,而是使用JSON加载数据...

这是错误:

    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

1 个答案:

答案 0 :(得分:1)

它不起作用,因为您正在使用a+模式打开文件。

json.load使用传递的类似文件的对象的.read方法。由于您使用的是a+模式,因此.read将返回一个空字符串(这很有意义,因为光标将位于文件的末尾)。

将模式更改为r(或不提供任何模式,默认为r),您的代码将可用。

或者,您可以在致电infile.seek(0)之前先致电json.load,但是我看不出使用a+模式的意义。

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']