Python 如何将数据附加到json文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12994442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to append data to a json file?
提问by Schiphol
I'm trying to create a function that would add entries to a json file. Eventually, I want a file that looks like
我正在尝试创建一个将条目添加到 json 文件的函数。最终,我想要一个看起来像的文件
[{"name" = "name1", "url" = "url1"}, {"name" = "name2", "url" = "url2"}]
etc. This is what I have:
等等,这就是我所拥有的:
def add(args):
with open(DATA_FILENAME, mode='r', encoding='utf-8') as feedsjson:
feeds = json.load(feedsjson)
with open(DATA_FILENAME, mode='w', encoding='utf-8') as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump(entry, feedsjson)
This does create an entry such as {"name"="some name", "url"="some url"}. But, if I use this addfunction again, with different name and url, the first one gets overwritten. What do I need to do to get a second (third...) entry appended to the first one?
这确实会创建一个条目,例如{"name"="some name", "url"="some url"}. 但是,如果我add再次使用此函数,使用不同的名称和 url,第一个将被覆盖。我需要做什么才能将第二个(第三个...)条目附加到第一个条目?
EDIT: The first answers and comments to this question have pointed out the obvious fact that I am not using feedsin the write block. I don't see how to do that, though. For example, the following apparently will not do:
编辑:这个问题的第一个答案和评论指出了我没有feeds在写块中使用的明显事实。不过,我不知道该怎么做。例如,以下显然不会:
with open(DATA_FILENAME, mode='a+', encoding='utf-8') as feedsjson:
feeds = json.load(feedsjson)
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump(entry, feeds)
采纳答案by SingleNegationElimination
json might not be the best choice for on-disk formats; The trouble it has with appending data is a good example of why this might be. Specifically, json objects have a syntax that means the whole object must be read and parsed in order to understand any part of it.
json 可能不是磁盘格式的最佳选择;附加数据的麻烦就是一个很好的例子,说明了为什么会这样。具体来说,json 对象的语法意味着必须读取和解析整个对象才能理解其中的任何部分。
Fortunately, there are lots of other options. A particularly simple one is CSV; which is supported well by python's standard library. The biggest downside is that it only works well for text; it requires additional action on the part of the programmer to convert the values to numbers or other formats, if needed.
幸运的是,还有很多其他选择。一个特别简单的就是 CSV;python的标准库很好地支持它。最大的缺点是它只适用于文本;如果需要,它需要程序员执行额外的操作以将值转换为数字或其他格式。
Another option which does not have this limitation is to use a sqlite database, which also has built-in support in python. This would probably be a bigger departure from the code you already have, but it more naturally supports the 'modify a little bit' model you are apparently trying to build.
没有此限制的另一个选项是使用 sqlite 数据库,该数据库在 python 中也具有内置支持。这可能与您已有的代码有更大的偏差,但它更自然地支持您显然正在尝试构建的“稍微修改一点”模型。
回答by Thomas
You aren't ever writing anything to do with the data you read in. Do you want to be adding the data structure in feeds to the new one you're creating?
您永远不会编写与您读入的数据有关的任何内容。您想将提要中的数据结构添加到您正在创建的新数据结构中吗?
Or perhaps you want to open the file in append mode open(filename, 'a')and then add your string, by writing the string produced by json.dumpsinstead of using json.dump- but nneonneo points out that this would be invalid json.
或者,您可能想以追加模式打开文件open(filename, 'a'),然后添加您的字符串,通过写入由json.dumps而不是使用生成的字符串json.dump- 但 nneonneo 指出这将是无效的 json。
回答by Susan Wright
Using ainstead of wshould let you update the file instead of creating a new one/overwriting everything in the existing file.
使用a而不是w应该让您更新文件而不是创建新文件/覆盖现有文件中的所有内容。
See this answerfor a difference in the modes.
请参阅此答案以了解模式的差异。
回答by nneonneo
You probably want to use a JSON listinstead of a dictionary as the toplevel element.
您可能希望使用 JSON列表而不是字典作为顶级元素。
So, initialize the file with an empty list:
因此,使用空列表初始化文件:
with open(DATA_FILENAME, mode='w', encoding='utf-8') as f:
json.dump([], f)
Then, you can appendnew entries to this list:
然后,您可以将新条目附加到此列表中:
with open(DATA_FILENAME, mode='w', encoding='utf-8') as feedsjson:
entry = {'name': args.name, 'url': args.url}
feeds.append(entry)
json.dump(feeds, feedsjson)
Note that this will be slow to execute because you will rewrite the full contents of the file every time you call add. If you are calling it in a loop, consider adding all the feeds to a list in advance, then writing the list out in one go.
请注意,这执行起来会很慢,因为每次调用add. 如果您在循环中调用它,请考虑提前将所有提要添加到列表中,然后一次性写出列表。
回答by NargesooTv
Append entry to the file contents if file exists, otherwise append the entry to an empty list and write in in the file:
如果文件存在,则将条目附加到文件内容,否则将条目附加到空列表并写入文件:
a = []
if not os.path.isfile(fname):
a.append(entry)
with open(fname, mode='w') as f:
f.write(json.dumps(a, indent=2))
else:
with open(fname) as feedsjson:
feeds = json.load(feedsjson)
feeds.append(entry)
with open(fname, mode='w') as f:
f.write(json.dumps(feeds, indent=2))
回答by SEDaradji
One possible solution is do the concatenation manually, here is some useful code:
一种可能的解决方案是手动进行连接,这里有一些有用的代码:
import json
def append_to_json(_dict,path):
with open(path, 'ab+') as f:
f.seek(0,2) #Go to the end of file
if f.tell() == 0 : #Check if file is empty
f.write(json.dumps([_dict]).encode()) #If empty, write an array
else :
f.seek(-1,2)
f.truncate() #Remove the last character, open the array
f.write(' , '.encode()) #Write the separator
f.write(json.dumps(_dict).encode()) #Dump the dictionary
f.write(']'.encode()) #Close the array
You should be careful when editing the file outside the script not add any spacing at the end.
在脚本外编辑文件时应该小心,不要在末尾添加任何间距。
回答by Matt
I have some code which is similar, but does not rewrite the entire contents each time. This is meant to run periodically and append a JSON entry at the end of an array.
我有一些类似的代码,但不会每次都重写整个内容。这意味着定期运行并在数组末尾附加一个 JSON 条目。
If the file doesn't exist yet, it creates it and dumps the JSON into an array. If the file has already been created, it goes to the end, replaces the ]with a ,drops the new JSON object in, and then closes it up again with another ]
如果该文件尚不存在,它会创建它并将 JSON 转储到一个数组中。如果文件已经被创建,它会走到最后,]用一个,删除新的 JSON 对象来替换它,然后用另一个再次关闭它]
# Append JSON object to output file JSON array
fname = "somefile.txt"
if os.path.isfile(fname):
# File exists
with open(fname, 'a+') as outfile:
outfile.seek(-1, os.SEEK_END)
outfile.truncate()
outfile.write(',')
json.dump(data_dict, outfile)
outfile.write(']')
else:
# Create file
with open(fname, 'w') as outfile:
array = []
array.append(data_dict)
json.dump(array, outfile)
回答by hassanzadeh.sd
this, work for me :
这个,为我工作:
with open('file.json', 'a') as outfile:
outfile.write(json.dumps(data))
outfile.write(",")
outfile.close()

