Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将JSON附加到文件_Python_Json - Fatal编程技术网

Python 将JSON附加到文件

Python 将JSON附加到文件,python,json,Python,Json,我试图将值附加到json文件中。如何附加数据?我已经尝试了很多方法,但没有一种有效 代码: 调用此函数时,如何将数据附加到json文件?我怀疑您遗漏了在尝试写入文件的块中出现TypeError。以下是您试图写的内容: with open('offline_post.json','a') as f: new = json.loads(f) new.update(a_dict) json.dump(new,f) 这里有几个问题。首先,将文件对象传递给json.loads命令

我试图将值附加到json文件中。如何附加数据?我已经尝试了很多方法,但没有一种有效

代码:


调用此函数时,如何将数据附加到json文件?

我怀疑您遗漏了在尝试写入文件的块中出现
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

其次,您将以追加模式打开文件,该模式将指针放在文件的末尾。当您运行
json.load
时,您不会得到任何东西,因为它是在文件末尾读取的。您需要在加载之前将其设置为0(编辑:由于附加模式不可读,因此无论如何都会失败)

第三,当您
json.dump
将新数据添加到文件中时,它会将新数据添加到旧数据之外的文件中。从结构上看,似乎要替换文件的内容(因为新数据已经包含旧数据)

您可能希望使用
r+
模式,
seek
在读写之间返回到文件的开头,并在结尾处
截断
以防数据结构的大小缩小

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)

我怀疑您漏掉了,您在尝试编写文件的块中遇到了
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

其次,您将以追加模式打开文件,该模式将指针放在文件的末尾。当您运行
json.load
时,您不会得到任何东西,因为它是在文件末尾读取的。您需要在加载之前将其设置为0(编辑:由于附加模式不可读,因此无论如何都会失败)

第三,当您
json.dump
将新数据添加到文件中时,它会将新数据添加到旧数据之外的文件中。从结构上看,似乎要替换文件的内容(因为新数据已经包含旧数据)

您可能希望使用
r+
模式,
seek
在读写之间返回到文件的开头,并在结尾处
截断
以防数据结构的大小缩小

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)

这是一种不同的方法,我只想在不重新加载所有数据的情况下进行追加。在一个树莓皮上运行,所以要注意内存。测试代码-

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
导入操作系统
json_文件_exists=0
filename=“/home/pi/scratch\u pad/test.json”
#删除上次运行的json数据
尝试:
删除(文件名)
除操作错误外:
通过
计数=0
锅炉=90
塔台=78

虽然count这是一种不同的方法,但我只想在不重新加载所有数据的情况下进行追加。在一个树莓皮上运行,所以要注意内存。测试代码-

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
导入操作系统
json_文件_exists=0
filename=“/home/pi/scratch\u pad/test.json”
#删除上次运行的json数据
尝试:
删除(文件名)
除操作错误外:
通过
计数=0
锅炉=90
塔台=78

然而,你能对不起作用的东西做一点扩展吗?您是否遇到了错误?再一次,创建一个隔离您的JSON问题的脚本将使人们更容易帮助您。这让你的问题变得比实际需要的更复杂,也让你的问题对未来的读者没那么有用。对不起。。编辑它。。现在检查/那好多了!只是一个小小的注释-我意识到这可能不是你真正的代码,但不要将
all
用作函数名,因为如果你这样做,你的名字会被掩盖。在python中调试gotcha是一个常见但很难的问题——你可以覆盖内置函数名,但你几乎永远都不想覆盖。你能在不起作用的地方扩展一下吗?您是否遇到了错误?再一次,创建一个隔离您的JSON问题的脚本将使人们更容易帮助您。这让你的问题变得比实际需要的更复杂,也让你的问题对未来的读者没那么有用。对不起。。编辑它。。现在检查/那好多了!只是一个小小的注释-我意识到这可能不是你真正的代码,但不要将
all
用作函数名,因为如果你这样做,你的名字会被掩盖。这是python中常见但很难调试的gotcha-您可以覆盖内置函数名,但您几乎不想覆盖。我发现list对象没有属性“update”error@user3041822听起来JSON被解释为一个列表。文件内容是什么?[{“body”:“uiewf”,“title”:“jk”,“id”:“25”,“author”:“ok”},{“body”:“hbjn”,“title”:“ghbj”,“id”:“27”,“author”:“vghbjn”}]@user3041822这是一个列表。您不能
更新它。如果您只是尝试向其添加另一个{“body”:…}dict,请使用
append
。那么如何将其作为JSON文件插入?我得到的列表对象没有属性“update”error@user3041822听起来JSON被解释为一个列表。文件内容是什么?[{“body”:“uiewf”,“title”:“jk”,“id”:“25”,“author”:“ok”},{“body”:“hbjn”,“title”:“ghbj”,“id”:“27”,“author”:“vghbjn”}]@user3041822这是一个列表。您不能
更新它。如果您只是尝试向它添加另一个{“body”:…}dict,请使用
append
。那么如何将其作为JSON文件插入?