我想将类保存到python中的文件.我想要这样的东西,我在python中有一个类似的类,就像这个C++结构:
struct WebSites
{
char SiteName[100];
int Rank;
};
Run Code Online (Sandbox Code Playgroud)
我想写这样的东西:
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();
}
Run Code Online (Sandbox Code Playgroud)
这可以简单地读取:
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;
}
Run Code Online (Sandbox Code Playgroud)
python中有一个方法可以做到这一点吗?
Python有pickle-module,可用于序列化对象.如果使用协议版本> = 1,则数据将序列化为二进制格式.你可以像这样使用泡菜:
class WebSites(object):
def __init__():
self.SiteName = ""
self.Rank = 0
import cPickle
# to serialize the object
with open("data.dump", "wb") as output:
cPickle.dump(WebSites(), output, cPickle.HIGHEST_PROTOCOL)
# to deserialize the object
with open("data.dump", "rb") as input:
obj = cPickle.load(input) # protocol version is auto detected
Run Code Online (Sandbox Code Playgroud)
Pickle处理嵌套对象和循环以及这样的坏东西,因此您可以轻松地使用它来序列化相当复杂的结构.请注意,存在一些限制,最明显的是pickle需要访问pickle对象的定义.