如何使用 python 将数据转储到 Json 文件中
How to dump data into Json file using python
如何将数据转储到 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'))
所以请解决我的问题......请帮助我
这只不过是遵循这种模式,所以你的代码错误是..你没有在 if 条件下正确定义文件模式
with open (cache_path. "t") as json_file:
而不是
with open (cache_path. "w") as json_file:
第二件事是你没有做转储数据
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))
如何将数据转储到 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'))
所以请解决我的问题......请帮助我
这只不过是遵循这种模式,所以你的代码错误是..你没有在 if 条件下正确定义文件模式
with open (cache_path. "t") as json_file:
而不是
with open (cache_path. "w") as json_file:
第二件事是你没有做转储数据
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))