使用Python保存和加载 字典 变量

使用Python保存和加载 字典 变量node_message

{'Conv_60': {'cosine-similarity': 0.77795, 'mse': 68.02103},
 'Conv_48': {'cosine-similarity': 0.78428, 'mse': 64.36318}
}

1 方法1

# node_message保存为text文件
filename = open('sensitivity_of_nodes.txt', 'w')
for node, sensitivity in node_message.items():
    filename.write(str(node) + ':' + str(sensitivity))
    filename.write('\n')
filename.close()
# 加载保存的text文件
node_message = {}
filename = open('sensitivity_of_nodes.txt')
for line in filename:
    line_split = line.split(':', 1) #按照第一个出现的':'进行分割
    node_message[line_split[0]] = line_split[1] #{str: str,...}
filename.close()

2 方法2

# node_message保存为json文件(推荐)
import json
save_json = json.dumps(node_message, sort_keys=False, indent=4, separators=(',', ': '))
filename = open('sensitivity_of_nodes.json', 'w')
filename.write(save_json)
filename.close()
# 加载保存的json文件
filename = open('sensitivity_of_nodes.json', 'r')
node_message = json.load(filename)
filename.close()

你可能感兴趣的:(日常生活学习记录,python,txt保存加载,json保存加载)