python中,将一些变量的数据写入到文本中,再从文本中读取出来继续使用
如字典、列表、numpy数据写入文本,再读取来,继续使用
字典与列表
def dict_write_to_txt_and_read_test():
dict_name = {1: {1: 2, 3: 4}, 2: {3: 4, 4: 5}}
f = open('temp.txt', 'w')
f.write(str(dict_name))
f.close()
# 读取
f = open('temp.txt', 'r')
a = f.read()
dict_name = eval(a)
print("read: \n", dict_name)
f.close()
if __name__ == '__main__':
dict_write_to_txt_and_read_test()
numpy数据写入到文本再读取
def dict_test():
'''
给字典增加键值对,
:return:
'''
import numpy as np
np.random.seed(1) # 指定生成“特定”的随机数-与seed 1 相关
conv_data_abs = {}
for layer_id in range(3):
L1_norm = np.random.random(2) * 10 # # 2 , 在[1,10)的区间上生成2个随机数
conv_data_abs[layer_id] = L1_norm
print(conv_data_abs)
print(conv_data_abs[1])
return conv_data_abs
def dict_write_numpy_to_txt_test():
import numpy as np
## 保存
dict_name = dict_test()
f = open('dict_write_to_txt_test.txt', 'w')
f.write(str(dict_name))
f.close()
from numpy import *
def dict_read_from_txt_test():
import numpy as np
print("dict_read_from_txt_test")
#
# b = np.loadtxt("dict_write_to_txt_test.txt", delimiter=',')
# print(b)
# 读取
f = open('dict_write_to_txt_test.txt', 'r')
a = f.read()
dict_name = eval(a)
print("dict_name:\n", dict_name)
print("dict_name[1]: ", dict_name[1])
print("type(dict_name[1]): ", type(dict_name[1]))
f.close()
if __name__ == '__main__':
# 含有numpy字典写入
dict_write_numpy_to_txt_test()
# 读取
dict_read_from_txt_test()