在python中保存和加载数据的最简单方法是什么,最好是以人类可读的输出格式?
我保存/加载的数据由两个浮点向量组成。理想情况下,这些向量应该在文件中命名(例如X和Y)。
我当前的save()
和load()
函数使用file.readline()
、file.write()
和字符串到浮点数的转换。一定有更好的东西。
发布于 2010-12-15 21:21:15
有几个选项--我不太清楚您喜欢什么。如果两个向量具有相同的长度,则可以使用numpy.savetxt()
将向量保存为列,例如x
和y
:
# 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。
发布于 2019-05-23 06:30:39
以下是编码器的一个示例,直到您可能想要为Body
类编写代码:
# 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))
下面是我想要序列化的类的示例:
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...
以下是序列化的方法:
# 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)
下面是转储的方法:
def dump_everything():
data = json.loads(open(FILE_NAME, "r").read())
return BodyEncoder.deserialize(data)
https://stackoverflow.com/questions/4450144
复制相似问题