python将字典、列表、numpy文件再读使用

35 篇文章 0 订阅
3 篇文章 0 订阅

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()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值