def import_pickle(selffilename)fh none tryfh open(filename"rb"magic fh read(len(gzip_magic)if magic =gzip_magicfh close(fh gzip open(filename"rb"elsefh seek( self clear(self update(pickle load(fh)return true except (environmenterrorpickle unpicklingerroras errprint("{ }import error{ }formatos path basename(sys argv[ ])err)return false finallyif fh is not nonefh close(we don' know whether the given file is compressed in either case we begin by opening the file in "read binarymodeand then we read the first two bytes if these bytes are the same as the gzip magic number we close the file and create new file object using the gzip open(function and if the file is not compressed we use the file object returned by open()calling its seek(method to restore the file pointer to the beginning so that the next read (made inside the pickle load(functionwill be from the start we can' assign to self since that would wipe out the incidentcollection object that is in useso instead we clear all the incidents to make the dictionary empty and then use dict update(to populate the dictionary with all the incidents from the incidentcollection dictionary loaded from the pickle note that it does not matter whether the processor' byte ordering is bigor little-endianbecause for the magic number we read individual bytesand for the data the pickle module handles endianness for us raw binary data with optional compression |writing our own code to handle raw binary data gives us complete control over our file format it should also be safer than using picklessince maliciously invalid data will be handled by our code rather than executed by the interpreter