美文网首页
python的list、dict的保存与读入

python的list、dict的保存与读入

作者: 137c | 来源:发表于2019-10-15 16:06 被阅读0次

list的保存

def savedata(data,filename):
    numpy_array = np.array(data)
    np.save(filename, numpy_array)

def readNp(filename):
    numpy_array = np.load(filename)  #numpy_array type, not list
    return numpy_array

dict的保存

import json
import datetime
import numpy as np

class JsonEncoder(json.JSONEncoder):

    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        elif isinstance(obj, datetime):                                 
            return obj.__str__()
        else:
            return super(MyEncoder, self).default(obj)

def save_dict(filename, dic):
    '''save dict into json file'''
    with open(filename,'w') as json_file:
        json.dump(dic, json_file, ensure_ascii=False, cls=JsonEncoder)

相关文章

网友评论

      本文标题:python的list、dict的保存与读入

      本文链接:https://www.haomeiwen.com/subject/uvzlmctx.html