簡體   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