如果需要按特定顺序保存大量词典,为什么不先将它们放在列表对象中,然后使用json为您序列化整个过程?
import json
def example():
# create a list of dictionaries
list_of_dictionaries = [
{'a': 0, 'b': 1, 'c': 2},
{'d': 3, 'e': 4, 'f': 5},
{'g': 6, 'h': 7, 'i': 8}
]
# Save json info to file
path = '.\\json_data.txt'
save_file = open(path, "wb")
json.dump(obj=list_of_dictionaries,
fp=save_file)
save_file.close()
# Load json from file
load_file = open(path, "rb")
result = json.load(fp=load_file)
load_file.close()
# show that it worked
print(result)
return
if __name__ == '__main__':
example()
如果您的应用程序必须不时附加新词典,则可能需要执行更接近以下内容的操作:
import json
def example_2():
# create a list of dictionaries
list_of_dictionaries = [
{'a': 0, 'b': 1, 'c': 2},
{'d': 3, 'e': 4, 'f': 5},
{'g': 6, 'h': 7, 'i': 8}
]
# Save json info to file
path = '.\\json_data.txt'
save_file = open(path, "w")
save_file.write(u'[')
save_file.close()
first = True
for entry in list_of_dictionaries:
save_file = open(path, "a")
json_data = json.dumps(obj=entry)
prefix = u'' if first else u', '
save_file.write(prefix + json_data)
save_file.close()
first = False
save_file = open(path, "a")
save_file.write(u']')
save_file.close()
# Load json from file
load_file = open(path, "rb")
result = json.load(fp=load_file)
load_file.close()
# show that it worked
print(result)
return
if __name__ == '__main__':
example_2()