首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在python中轻松保存/加载数据

在python中轻松保存/加载数据
EN

Stack Overflow用户
提问于 2010-12-15 21:02:10
回答 5查看 57.5K关注 0票数 13

在python中保存和加载数据的最简单方法是什么,最好是以人类可读的输出格式?

我保存/加载的数据由两个浮点向量组成。理想情况下,这些向量应该在文件中命名(例如X和Y)。

我当前的save()load()函数使用file.readline()file.write()和字符串到浮点数的转换。一定有更好的东西。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2010-12-15 21:21:15

有几个选项--我不太清楚您喜欢什么。如果两个向量具有相同的长度,则可以使用numpy.savetxt() 将向量保存为列,例如xy

代码语言:javascript
复制
 # saving:
 f = open("data", "w")
 f.write("# x y\n")        # column names
 numpy.savetxt(f, numpy.array([x, y]).T)
 # loading:
 x, y = numpy.loadtxt("data", unpack=True)

如果您正在处理更大的浮点数向量,则无论如何都应该使用NumPy。

票数 9
EN

Stack Overflow用户

发布于 2010-12-15 21:04:05

一种简单的序列化格式是JSON,它便于人类和计算机读取。

您可以使用json Python模块。

票数 2
EN

Stack Overflow用户

发布于 2019-05-23 06:30:39

以下是编码器的一个示例,直到您可能想要为Body类编写代码:

代码语言:javascript
复制
# add this to your code
class BodyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.ndarray):
            return obj.tolist()
        if hasattr(obj, '__jsonencode__'):
            return obj.__jsonencode__()
        if isinstance(obj, set):
            return list(obj)
        return obj.__dict__

    # Here you construct your way to dump your data for each instance
    # you need to customize this function
    def deserialize(data):
        bodies = [Body(d["name"],d["mass"],np.array(d["p"]),np.array(d["v"])) for d in data["bodies"]]
        axis_range = data["axis_range"]
        timescale = data["timescale"]
        return bodies, axis_range, timescale

    # Here you construct your way to load your data for each instance
    # you need to customize this function
    def serialize(data):
        file = open(FILE_NAME, 'w+')
        json.dump(data, file, cls=BodyEncoder, indent=4)
        print("Dumping Parameters of the Latest Run")
        print(json.dumps(data, cls=BodyEncoder, indent=4))

下面是我想要序列化的类的示例:

代码语言:javascript
复制
class Body(object):
    # you do not need to change your class structure
    def __init__(self, name, mass, p, v=(0.0, 0.0, 0.0)):
        # init variables like normal
        self.name = name
        self.mass = mass
        self.p = p
        self.v = v
        self.f = np.array([0.0, 0.0, 0.0])

    def attraction(self, other):
        # not important functions that I wrote...

以下是序列化的方法:

代码语言:javascript
复制
# you need to customize this function
def serialize_everything():
    bodies, axis_range, timescale = generate_data_to_serialize()

    data = {"bodies": bodies, "axis_range": axis_range, "timescale": timescale}
    BodyEncoder.serialize(data)

下面是转储的方法:

代码语言:javascript
复制
def dump_everything():
    data = json.loads(open(FILE_NAME, "r").read())
    return BodyEncoder.deserialize(data)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4450144

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档