Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save a class into a binary file - Python

I'm aware that saving a class into a binary file in c++ is possible using:

file.write(Class_variable, size_of_class, amount_of_saves, file_where_to_save)

or something similar, and I wanted to use that in python in order to make it easier to write and read lots of data.

I've tried to do this:

def Save_Game(player, room):
    address = 'Saves/player'

    file = open(address, 'wb')
    file.write(player)

    address = 'Saves/room'

    file = open(address, 'wb')
    file.write(room)

Room and player being class_objects. But it says:

TypeError: must be convertible to a buffer, not PlayerMarty

What can I do?

like image 209
Kikadass Avatar asked Aug 30 '15 11:08

Kikadass


People also ask

Can Python handle binary files?

In Python, the IO module provides methods of three types of IO operations; raw binary files, buffered binary files, and text files. The canonical way to create a file object is by using the open() function.


2 Answers

pickle is what you need. The pickle module implements a fundamental, but powerful algorithm for serializing and de-serializing a Python object structure. This is an example

import pickle

class MyClass:
    def __init__(self,name):
        self.name = name
    def display(self):
        print(self.name)

my = MyClass("someone")
pickle.dump(my, open("myobject", "wb"))
me = pickle.load(open("myobject", "rb"))
me.display()
like image 141
nishparadox Avatar answered Sep 28 '22 22:09

nishparadox


You can get at the bytes of Python objects to save & restore them like that, but it's not easy to do directly. However, the standard pickle module simplifies the process enormously.

like image 30
PM 2Ring Avatar answered Sep 28 '22 21:09

PM 2Ring