[英]How to write each JSON objects in a newline of JSON file? (Python)
我遇到了問題,實際上我有一個JSON文件,其中每個對象都在一行中。 因此,如果有100個對象,則會有100行。
[{ "attribute1" : "no1", "attribute1": "no2"}
{ "attribute1" : "no12", "attribute1": "no22"}]
我打開這個JSON文件,並刪除每個元素的一些atttributes。
然后,我想以相同的方式將對象寫回文件(1對象= 1行)。
我試圖用“縮進”和“分隔符”這樣做,但它不起作用。
我想擁有 :
[{ "attribute1": "no2"}
{"attribute1": "no22"}]
謝謝閱讀。
with open('verbes_lowercase.json','r+',encoding='utf-8-sig') as json_data:
data=json.load(json_data)
for k in range(len(data)):
del data[k]["attribute1"]
json.dump(data,json_data,ensure_ascii=False , indent='1', separators=(',',':'))
json_data.seek(0)
json_data.truncate()
我用一個技巧來做我想做的事,將所有對象重寫成一個新行。 我將要保留的內容寫入新文件中。
with open('verbes_lowercase.json','r',encoding='utf-8-sig') as json_data:
data=json.load(json_data)
with open("verbes.json",'w',encoding="utf-8-sig") as file:
file.write("[")
length=len(data)
for k in range(0,length):
del data[k]["attribute1"]
if (k!=length-1):
file.write(json.dumps(data[k], ensure_ascii=False)+",\n")
else:
file.write(json.dumps(data[length-1], ensure_ascii=False)+"]")
正如我在代碼中提到的,如果你想使用json的大文件,你將不得不尋找另一種方式
import json
def write(file_object, dictionary_object):
file_object.write(json.dumps(dictionary_object).replace('"},', '"},\n'))
def safe_write(file_object, dictionary_object):
file_object.truncate(0)
file_object.write(json.dumps(dictionary_object).replace('"},', '"},\n'))
# Easy But Bad For Big Json Files
dict_object = [{"attribute1": "no1", "attribute12": "no2"}, {"attribute1": "no12", "attribute12": "no22"}, {"attribute1": "no13", "attribute12": "no23"}, {"attribute1": "no14", "attribute12": "no24"}]
with open('json_dump.txt', 'w') as f:
write(f, dict_object) # Writes Perfectly
dict_object.append({"attribute1": "no15", "attribute12": "no25"})
safe_write(f, dict_object) # Writes Perfectly (We used the safe_write function to avoid appending to the end of the file) (Actually we can seek to the file's start but if you removed a element from list this makes the file shorter and the start of the file will be written out but the end of the file will still remain)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.