我正在尝试将值附加到一个json文件中。如何追加数据?我已经尝试了这么多方法,但都不起作用?
代码:
def all(title,author,body,type):
title = "hello"
author = "njas"
body = "vgbhn"
data = {
"id" : id,
"author": author,
"body" : body,
"title" : title,
"type" : type
}
data_json = json.dumps(data)
#data = ast.literal_eval(data)
#print data_json
if(os.path.isfile("offline_post.json")):
with open('offline_post.json','a') as f:
new = json.loads(f)
new.update(a_dict)
json.dump(new,f)
else:
open('offline_post.json', 'a')
with open('offline_post.json','a') as f:
new = json.loads(f)
new.update(a_dict)
json.dump(new,f)
如何在调用此函数时将数据追加到json文件?
发布于 2016-01-25 14:45:03
我怀疑您遗漏了在尝试写入文件的块中获取TypeError
。这是你想要写的地方:
with open('offline_post.json','a') as f:
new = json.loads(f)
new.update(a_dict)
json.dump(new,f)
这里有几个问题。首先,将一个文件对象传递给json.loads
命令,该命令需要一个字符串。您可能打算使用json.load
。
其次,在append模式下打开文件,将指针放在文件的末尾。当您运行json.load
时,您不会得到任何东西,因为它是在文件末尾读取的。在load
ing之前,您需要将seek
设置为0(编辑:这无论如何都会失败,因为追加模式不可读)。
第三,当您将新数据json.dump
到文件时,除了旧数据之外,它还会将新数据附加到文件中。从结构上看,您似乎希望替换文件的内容(因为新数据已经包含旧数据)。
您可能希望使用r+
模式,在读取和写入之间返回到文件的开头,并在结束时使用truncate
,以防数据结构的大小缩小。
with open('offline_post.json', 'r+') as f:
new = json.load(f)
new.update(a_dict)
f.seek(0)
json.dump(new, f)
f.truncate()
或者,您可以打开该文件两次:
with open('offline_post.json', 'r') as f:
new = json.load(f)
new.update(a_dict)
with open('offline_post.json', 'w') as f:
json.dump(new, f)
发布于 2016-03-04 02:19:28
这是一种不同的方法,我只是想在不重新加载所有数据的情况下进行追加。在覆盆子pi上运行,所以我想关注内存。测试代码-
import os
json_file_exists = 0
filename = "/home/pi/scratch_pad/test.json"
# remove the last run json data
try:
os.remove(filename)
except OSError:
pass
count = 0
boiler = 90
tower = 78
while count<10:
if json_file_exists==0:
# create the json file
with open(filename, mode = 'w') as fw:
json_string = "[\n\t{'boiler':"+str(boiler)+",'tower':"+str(tower)+"}\n]"
fw.write(json_string)
json_file_exists=1
else:
# append to the json file
char = ""
boiler = boiler + .01
tower = tower + .02
while(char<>"}"):
with open(filename, mode = 'rb+') as f:
f.seek(-1,2)
size=f.tell()
char = f.read()
if char == "}":
break
f.truncate(size-1)
with open(filename, mode = 'a') as fw:
json_string = "\n\t,{'boiler':"+str(boiler)+",'tower':"+str(tower)+"}\n]"
fw.seek(-1, os.SEEK_END)
fw.write(json_string)
count = count + 1
https://stackoverflow.com/questions/34993995
复制相似问题