简体   繁体   English

python 如果不存在则创建 json 文件,否则追加

[英]python create json file if it doesn't exist otherwise append

I have some json data source and want to either create an output file and write the first payload to that file, otherwise (if the file already exists) I want to append to it.我有一些 json 数据源,并且想要创建一个输出文件并将第一个有效负载写入该文件,否则(如果该文件已经存在)我想附加到它。 But I can't seem to do it:但我似乎做不到:

import json
import time

data = {'key1': 1, 'key2': {'k2a': 2.1, 'k2b': 2.2}}

fname = 'test.json'

with open(fname, 'a+') as f:
    try:
        loaded = json.load(f)
        loaded.append({'appended': time.time()})
    except json.decoder.JSONDecodeError as e:
        print(e)
        loaded = [data]
    
    json.dump(loaded, f)

On the first run of that code it creates the json file as expected.在该代码的第一次运行时,它会按预期创建 json 文件。 However on the second it prints out Expecting value: line 1 column 1 (char 0) , meaning the try block doesn't correctly execute, and the end result in the file is: [{ "key1": 1, "key2": { "k2a": 2.1, "k2b": 2.2 }}][{"key1": 1, "key2": {"k2a": 2.1, "k2b": 2.2}}] which is clearly not correct.但是在第二个它打印出Expecting value: line 1 column 1 (char 0) ,这意味着 try 块没有正确执行,文件中的最终结果是: [{ "key1": 1, "key2": { "k2a": 2.1, "k2b": 2.2 }}][{"key1": 1, "key2": {"k2a": 2.1, "k2b": 2.2}}]这显然是不正确的。

I think this is a really convoluted way to accomplish something that must be a very common task, but surely there is a straightforward way?我认为这是一种非常复杂的方式来完成必须是一项非常常见的任务,但肯定有一种简单的方式吗? I've looked but many examples just append to pre-existing files.我看过但很多例子只是附加到预先存在的文件中。

You cannot append to a json-file as such.您不能像这样附加到 json 文件。 See the json file as one (serialized) python object, in your case a dictionary.将 json 文件视为一个(序列化)python 对象,在您的情况下是字典。

You could load the json file (if it's there), and if not initialise it as en empty dict.您可以加载 json 文件(如果它在那里),如果没有将其初始化为 en empty dict。

Then add the data that you wish and save it again (in one piece).然后添加您希望的数据并再次保存(一件)。

import json
import time

fname = 'test.json'

loaded = {}
try:
    with open(fname, "r") as f:
        loaded = json.load(f)
except IOError:
    # may complain to user as well
    pass

loaded['appended'] = time.time()

with open(fname, "w") as f:
    json.dump(loaded, f)

I don't think you can append using json.dump, you'll have to handle it with something like this.我不认为你可以使用 json.dump 追加,你必须用这样的东西来处理它。

import os
import json
import time
fname = "test.json"
data = {'key1': 1, 'key2': {'k2a': 2.1, 'k2b': 2.2}}

if os.path.exists(fname):
    #read existing file and append new data
    with open(fname,"r") as f:
        loaded = json.load(f)
    loaded.append({'appended': time.time()})
else:
    #create new json
    loaded = [data]

#overwrite/create file
with open(fname,"w") as f:
    json.dump(loaded,f)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM