How to dump data into Json file

import time
import json
import os


def long_function(name):
    cache_path = 'cache.json'
    if not os.path.isfile(cache_path):
        with open(cache_path, 't') as json_file:
            cache_file_data = [name]
            jsondump(cache_file_data, json_file)
    else:
        with open(cache_path, 'r') as json_file:
            cache_file_data = json.load(json_file)

    if name in cache_file_data:
        print("Name already exist")
        return name
    else:
        cache_file_data.append(name)
        for e in range(5):
            time.sleep(1)
            print(e+1)
        with open(cache_path, 'w') as json_file:
            jsondump(cache_file_data, json_file)
            print("New Name added in cache")
            return name


print(long_function('nitu'))

so please resolve my problem......please help me

推荐答案

这只是遵循这个模式,你的代码错误是..在if条件下,您没有正确定义文件模式

with open (cache_path. "t") as json_file:

而不是

with open (cache_path. "w") as json_file:

第二件事是你没有做转储数据的工作

Python相关问答推荐

使用Python异步地持久跟踪用户输入

为用户输入的整数查找根/幂整数对的Python练习

Django.core.exceptions.SynchronousOnlyOperation您不能从异步上下文中调用它-请使用线程或SYNC_TO_ASYNC

分解polars DataFrame列而不重复其他列值

在一个数据帧中,我如何才能发现每个行号是否出现在一列列表中?

大型稀疏CSR二进制矩阵乘法结果中的错误

正则表达式反向查找

为什么这个正则表达式没有捕获最后一次输入?

如何在networkx图中提取和绘制直接邻居(以及邻居的邻居)?

如何使用count()获取特定日期之间的项目

如何更改网络中某条边的位置(&Q;)?

使用BeautifulSoap库从Web获取表格时没有响应

获取给出特定产品的所有可能组合的数量

在Django管理后台保存模型时保存当前用户

没有与提供的参数匹配

在连接redis到django和docker之后,数据不会保存在redis-tags中

用Gekko拟合两个总体的测量值

在matplotlib中将标题的一部分设置为粗体和正常

从Pandas Dataframe导出Excel透视表

如何在0.20.7之前的版本中实现POLARS';之前的`vot()‘功能?