如何使用Python将数据转储到JSON文件中

3

如何将数据导入Json文件 *如下Python代码所示,我正在尝试将数据转储到Json文件中,但我在编写Python代码时遇到了困难*

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'))

所以请解决我的问题......请帮我


没有 't' 这种打开模式。你要么想用 'w' 写入,要么想用 'r' 读取文件。此外,你需要的函数是 json.dump,而不是 jsondump。为什么要睡5秒钟?这会让你的用户感到烦恼。 - Tim Roberts
@TimRoberts 模式 't' 确实存在。它甚至是默认值。你可能看的是 Python 2 的文档吧? - Kelly Bundy
2个回答

1
import json
  
# JSON data:
x =  '{ "organization":"New_holn",
        "city":"Noida",
        "country":"India"}'
 
# python object to be appended
y = {"pin":117845}
 
# parsing JSON string:
z = json.loads(x)
  
# appending the data
z.update(y)
 
# the result is a JSON string:
print(json.dumps(z))

0

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

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

不是

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

另外一件事是你没有进行数据转储


1
他试图转储数据。告诉他如何修复它。这就是答案所做的。 - Tim Roberts

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接