python使用marshal模块序列化实例
本文实例讲述了python使用marshal模块序列化的方法,分享给大家供大家参考。具体方法如下:
先来看看下面这段代码:
importmarshal data1=['abc',12,23,'jb51']#几个测试数据 data2={1:'aaa',"b":'dad'} data3=(1,2,4) output_file=open("a.txt",'wb')#把这些数据序列化到文件中,注:文件必须以二进制模式打开 marshal.dump(data1,output_file) marshal.dump(data2,output_file) marshal.dump(data3,output_file) output_file.close() input_file=open('a.txt','rb')#从文件中读取序列化的数据 #data1=[] data1=marshal.load(input_file) data2=marshal.load(input_file) data3=marshal.load(input_file) printdata1#给同志们打印出结果看看 printdata2 printdata3 outstring=marshal.dumps(data1)#marshal.dumps()返回是一个字节串,该字节串用于写入文件 open('out.txt','wb').write(outstring) file_data=open('out.txt','rb').read() real_data=marshal.loads(file_data) printreal_data
结果:
['abc',12,23,'jb51'] {1:'aaa','b':'dad'} (1,2,4) ['abc',12,23,'jb51']
marshel模块的几个函数官方描述如下:
Themoduledefinesthesefunctions:
marshal.dump(value,file[,version])
Writethevalueontheopenfile.Thevaluemustbeasupportedtype.Thefilemustbeanopenfileobjectsuchassys.stdoutorreturnedbyopen()oros.popen().Itmustbeopenedinbinarymode('wb'or'w+b').
Ifthevaluehas(orcontainsanobjectthathas)anunsupportedtype,aValueErrorexceptionisraised—butgarbagedatawillalsobewrittentothefile.Theobjectwillnotbeproperlyreadbackbyload().
Newinversion2.4:Theversionargumentindicatesthedataformatthatdumpshoulduse(seebelow).
marshal.load(file)
Readonevaluefromtheopenfileandreturnit.Ifnovalidvalueisread(e.g.becausethedatahasadifferentPythonversion'sincompatiblemarshalformat),raiseEOFError,ValueErrororTypeError.Thefilemustbeanopenfileobjectopenedinbinarymode('rb'or'r+b').
Warning
Ifanobjectcontaininganunsupportedtypewasmarshalledwithdump(),load()willsubstituteNonefortheunmarshallabletype.
marshal.dumps(value[,version])
Returnthestringthatwouldbewrittentoafilebydump(value,file).Thevaluemustbeasupportedtype.RaiseaValueErrorexceptionifvaluehas(orcontainsanobjectthathas)anunsupportedtype.
Newinversion2.4:Theversionargumentindicatesthedataformatthatdumpsshoulduse(seebelow).
marshal.loads(string)
Convertthestringtoavalue.Ifnovalidvalueisfound,raiseEOFError,ValueErrororTypeError.Extracharactersinthestringareignored.
Inaddition,thefollowingconstantsaredefined:
marshal.version
Indicatestheformatthatthemoduleuses.
marshal.version的用处:marshal不保证不同的python版本之间的兼容性,所以保留个版本信息的函数.
希望本文所述对大家Python程序设计的学习有所帮助。