简体   繁体   English

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

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

The error occurs if I try to convert the json file into a variable and try to convert the file again to a separate variable is throws and error.如果我尝试将 json 文件转换为变量并尝试再次将文件转换为单独的变量,则会出现错误并抛出错误。 I thought that json.load converts a json object to the python equivalent.我认为 json.load 将 json object 转换为 python 等效项。 So I am confused on why calling json.load(file) again would cause an error.所以我很困惑为什么再次调用 json.load(file) 会导致错误。 Is the file still open or being used by the first call?文件是否仍然打开或被第一次调用使用? I know I can get around it, I am just trying to understand json and the error.我知道我可以解决它,我只是想了解 json 和错误。 Using python 3.9.使用 python 3.9。

#This code works: #此代码有效:

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)

#This code with the extra conversion to a new variable fails with error #这段代码额外转换为新变量失败并出现错误

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)

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

In your second set of code, the first json.load() reads all of the data in the file and leaves the read pointer at the end of the file.在您的第二组代码中,第一个 json.load() 读取文件中的所有数据并将读取指针留在文件末尾。 the subsequent.load() call gets a empty string which results in the error you get.随后的.load() 调用会得到一个空字符串,这会导致您得到错误。 You either need to:您要么需要:

  1. have your two json blobs in different files and read them separately or将您的两个 json blob 放在不同的文件中并分别阅读它们或
  2. you need to use loads() to load the json object from a string and manage the data in the file with read operations that read part of the file that contains the individual sections of json.您需要使用loads()从字符串中加载json object,并通过读取包含json各个部分的部分文件的读取操作来管理文件中的数据。 you would read the data in as a string then pass it to loads()您可以将数据作为字符串读取,然后将其传递给loads()

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

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