如何将数据导入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't'
确实存在。它甚至是默认值。你可能看的是 Python 2 的文档吧? - Kelly Bundy