Logan Darby Logan Darby - 3 months ago 31
Python Question

How would I write an object to a file for later use?

In a program I am creating, I have to write a

object to a file, so I can use it later. How would I go about doing this?


You can use the pickle module, although you have to implement some functions to make it work. This is assuming you want to save the state of the things being done in the thread, instead of the thread itself, which is handled by the operating system and can't be serialized in a meaningful way.

import pickle


class MyThread(threading.Thread):
    def run(self):
        ...  # Add the functionality. You have to keep track of your state in a manner that is visible to other functions by using "self." in front of the variables that should be saved

    def __getstate__(self):
        ...  # Return a pickable object representing the state

    def __setstate__(self, state):
        ...  # Restore the state. You may have to call the "__init__" method, but you have to test it, as I am not sure if this is required to make the resulting object function as expected. You might run the thread from here as well, if you don't, it has to be started manually.

To save the state:

pickle.dump(thread, "/path/to/file")

To load the state:

thread = pickle.load("/path/to/file")