I have want to save classes to a file in python.
I want something like this, I have a similar class in python, like this C++ struct:
struct WebSites
{
char SiteName[100];
int Rank;
};
and I want to write something like this:
void write_to_binary_file(WebSites p_Data)
{
fstream binary_file("c:\\test.dat",ios::out|ios::binary|ios::app);
binary_file.write(reinterpret_cast<char *>(&p_Data),sizeof(WebSites));
binary_file.close();
}
which could be read simply by this:
void read_from_binary_file()
{
WebSites p_Data;
fstream binary_file("c:\\test.dat",ios::binary|ios::in);
binary_file.read(reinterpret_cast<char *>(&p_Data),sizeof(WebSites));
binary_file.close();
cout<<p_Data.SiteName<<endl;
cout<<"Rank :"<< p_Data.Rank<<endl;
}
is there a method in python to do this?
Python has the
pickle-module that can be used to serialize objects. If you use a protocol version >= 1, the data is serialized to a binary format. You can use pickle like this:Pickle takes care of nested objects and cycles and bad stuff like this, so you can easily serialize quite complex structures with it. Note that there are some limitations, most notably pickle requires access to the definitions of the pickled objects.