上文中提到PyQt的QDataStream类对Python类型和PyQt类型的数据进行读写操作,同样python自身提供了标准pickle模块可对任意的python数据结构进行存储和读写,当然pickle模块可以对Qt的数据类型进行存储和读写。其实QDataStream类和pickle模块大同小异的,但是在实践建议,当利用PyQt写Gui程序时,最好还是利用QDataStream类,因为它针对Qt类型更有效果。写标准的python程序,则利用pickle模块。
以下例子为创建一个类型结构Movie,包含的数据类型都是标准的python类型,然后将此类型通过pickle模块保存到二进制文件,然后从二进制文件将保存的内容读出。与上文提到的QDataStream类非常类似。
import pickle
import gzip
import os
import datetime
class Movie(object):
UNKNOWNYEAR = 1890
UNKNOWNMINUTES = 0
def __init__(self, title=None, year=UNKNOWNYEAR,
minutes=UNKNOWNMINUTES, acquired=None, notes=None):
self.title = title
self.year = year
self.minutes = minutes
self.acquired = (acquired if acquired is not None
else datetime.date.today())
self.notes = notes
class MovieContainer(object):
def __init__(self,fname,movies):
self.__fname = fname
self.__movies = movies
def savePickle(self):
error = None
fh = None
try:
fh = gzip.open(str(self.__fname), "wb")
pickle.dump(self.__movies, fh, 2)
except EnvironmentError as e:
error = "Failed to save: {0}".format(e)
finally:
if fh is not None:
fh.close()
if error is not None:
print(error)
print("Saved 1 movie records to {0}".format(
os.path.basename(self.__fname)))
def loadPickle(self):
error = None
fh = None
try:
fh = gzip.open(str(self.__fname), "rb")
self.__movies = pickle.load(fh)
except EnvironmentError as e:
error = "Failed to load: {0}".format(e)
finally:
if fh is not None:
fh.close()
if error is not None:
print(error)
print("Loaded 1 movie records from {0}".format(
os.path.basename(self.__fname)) )
print(self.__movies.title,self.__movies.year,self.__movies.minutes,self.__movies.acquired,self.__movies.notes)
if __name__ == "__main__":
#textdata=[["god save",1989,45,None,"test data god save"],
#["queen save",1960,56,None,"test data queen save"],
#["HK save",1990,66,None,"test data HK save"],
#["US save",2010,99,None,"test data US save"]]
textdata=[["God save world",1989,45,None,"HELLO WORLD"]]
fname="/home/yrd/work/movie.pickle"
for data in textdata:
movie=Movie(data[0],data[1],data[2],data[3],data[4])
moviecontainer=MovieContainer(fname, movie)
moviecontainer.savePickle()
moviecontainer.loadPickle()
执行结果:
Saved 1 movie records to movie.pickle
Loaded 1 movie records from movie.pickle
God save world 1989 45 2017-01-14 HELLO WORLD