任何人都可以告訴我我需要使用什么方式從包含元組的 JSON 檔案中獲取最后一行?
lst = (('7', '?'), ('7', '?')) # this line is generated each time and has new values
例如,“deals.json”檔案包含以下幾行:
[["7", "\u2660"], ["7", "\u2663"]]
[["8", "\u2660"], ["8", "\u2663"]]
代碼:
# here I add new line into the file
with open('deals.json', 'a') as f:
json.dump(lst,f)
f.write('\n')
# here I want to read the last line and handle it
with open('deals.json') as f:
json_data = json.load(f)
print(json_data)
運行此代碼后,它作業正常,但在第二個之后,它在嘗試讀取檔案時失敗,很明顯:
json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 549)
我知道如何使用文本檔案來做到這一點,但不知道如何讀取包含元組的 JSON 中的最后一行。
uj5u.com熱心網友回復:
可以這樣實作只讀取最后一行。在內部將讀取整個檔案,但您不需要明確處理。如果檔案非常大,那么您可能需要另一種方法。
import json
with open('deals.json') as f:
j = json.loads(f.readlines()[-1])
print(j)
輸出:
[['8', '?'], ['8', '?']]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/384556.html
