繁体   English   中英

Python 再次在同一文件上使用 json.load 时出错

[英]Python Error when using json.load on the same file again

如果我尝试将 json 文件转换为变量并尝试再次将文件转换为单独的变量,则会出现错误并抛出错误。 我认为 json.load 将 json object 转换为 python 等效项。 所以我很困惑为什么再次调用 json.load(file) 会导致错误。 文件是否仍然打开或被第一次调用使用? 我知道我可以解决它,我只是想了解 json 和错误。 使用 python 3.9。

#此代码有效:

def scores2(filedir):
    for filename in os.listdir(filedir):
        with open(os.path.join(filedir, filename), 'r') as read_file:
            data = json.load(read_file)

#这段代码额外转换为新变量失败并出现错误

def scores2(filedir):
    for filename in os.listdir(filedir):
        with open(os.path.join(filedir, filename), 'r') as read_file:
            data = json.load(read_file)
            dataextra= json.load(read_file)

错误是从 None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) 引发 JSONDecodeError("Expecting value", s, err.value)

在您的第二组代码中,第一个 json.load() 读取文件中的所有数据并将读取指针留在文件末尾。 随后的.load() 调用会得到一个空字符串,这会导致您得到错误。 您要么需要:

  1. 将您的两个 json blob 放在不同的文件中并分别阅读它们或
  2. 您需要使用loads()从字符串中加载json object,并通过读取包含json各个部分的部分文件的读取操作来管理文件中的数据。 您可以将数据作为字符串读取,然后将其传递给loads()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM