在python中轻松保存/加载数据 [英] easy save/load of data in python

查看:117
本文介绍了在python中轻松保存/加载数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the easiest way to save and load data in python, preferably in a human-readable output format?

我保存/加载的数据包括两个浮游物的向量。理想情况下,这些向量将在文件中命名(例如X和Y)。

The data I am saving/loading consists of two vectors of floats. Ideally, these vectors would be named in the file (e.g. X and Y).

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

My current save() and load() functions use file.readline(), file.write() and string-to-float conversion. There must be something better.

推荐答案

有几个选项 - 我不知道你喜欢什么。如果两个向量具有相同的长度,则可以使用 numpy.savetxt() 保存你的向量,比如 x y ,作为列:

There are several options -- I don't exactly know what you like. If the two vectors have the same length, you could use numpy.savetxt() to save your vectors, say x and y, as columns:

 # 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。

If you are dealing with larger vectors of floats, you should probably use NumPy anyway.

这篇关于在python中轻松保存/加载数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆