Sergio Cavaleiro Costa
Sergio Cavaleiro Costa

Reputation: 560

Python write object properties to file

I am solving a n-body simulation problem using Python OOP. Each of my particles is an object with properties such as mass, position, velocity, etc, and I would like to every few simulation time write particle's properties to a file. So, each particle would have a file, and each line would have its properties in a particular time. So for instance, my class would be something like,

from numpy import mod

class Particle(object):
    def __init__(self):
        self.idx = 3        # particle id
        self.t = 0.7        # s
        self.mass = 20.     # kg
        self.x = 20.        # m
        self.y = 30.        # m
        self.dt2store = 0.7 # s (simulated time)

    def store(self):
        if mod(self.t, self.dt2store):
            self.writer()

    def writer(self):
        '''
        It stores data in particle id3 file
        data2store = [self.t, self.mass, self.x, self.y]
        '''

What is the best, more efficient way of doing such?

Thank you for the help.

Upvotes: 2

Views: 3631

Answers (1)

In python, there is a library called Pickle that allows you to serialize or de-serialize objects. It is not very efficient when compared with other libraries such as JSON and raises some security issue (you can check it here). But it provides an easy way to write and load objects with the methods:

  • pickle.dump(obj, file, protocol=None, *, fix_imports=True)
  • pickle.load(file, *, fix_imports=True, encoding="ASCII", errors="strict")

Another alternative would be to use the JSON library methods:

  • json.dump
  • json.load

But in this case, you would have to transform your object into some built-in data type that the JSON library accepts like dict, list or tuple and in case you need the object when you load it, you would have to recreate it. Something like this:

with open('particle1.json', 'w') as fp:
  json.dump({'idx': particle.idx, 't': particle.t }, fp)

particle = Particle()
with open('particle1.json', 'r') as fp:
  particle_properties = json.load(fp)
  particle.idx = particle_properties['idx']
  particle.t = particle_properties['t']

Upvotes: 1

Related Questions