[Tutor] Need help printing a pickled data

Matt D md123 at nycap.rr.com
Tue Jun 25 02:36:29 CEST 2013


On 06/24/2013 07:17 PM, Alan Gauld wrote:
> On 24/06/13 23:05, Matt D wrote:
>> I have been unable to find a way to write pickled data to text file.
> 
> Probably because pickled data is not plain text.
> You need to use binary mode. However...
> 
> 
>>      def __init__(self, data):
>>          wx.PyEvent.__init__(self)
>>          self.SetEventType (wxDATA_EVENT)
>>          # and this is the actual data
>>          self.data = data
>>          with open('mypicklelog.txt','a') as log:
>>              log.write(self.data)
> 
> Since you are not using pickle here, all you are really doing
> is trying to write whatever data is to a text file that
> happens to have 'pickle' in its name.
> 
> When writing to a text file you need to write strings.
> You have no guarantee that 'data' is a string. You should
> probably convert it before writing it. Thats one of the
> advantages of using real pickles - they take care of
> that complication for you.
> 
>> I cant figure out why these last two line dont write to the .txt file
>> after the program has received the pickled Python dictionary?
> 
> Pickle data has to be unpickled before you can use it.
> Before you can write it back again you need to repickle it.
> The code you posted does not show you producing and pickled
> data nor indeed you reading any pickled data...
> 
> If 'data' is indeed in pickle format you cannot simply write
> it to a text file since Pickle is not in a text format.
> 
> 
im sorry; some more code will clarify i think ;

class DataEvent(wx.PyEvent):
   # the values of the text fields get passed into the constructor
inside of data
    def __init__(self, data):
        wx.PyEvent.__init__(self)
        # this line *binds* this class to a certain type of event,
wxDATA_EVENT
        self.SetEventType (wxDATA_EVENT)
        # and this is the actual data
        self.data = data
        with open('mypicklelog.txt','a') as log:
            log.write(self.data)

self.data stores the data as a dictionary.  from lower inthe program:

 # Display the values on the UI
    def display_data(self,event):
        #gets the "message" into the event object
        #message is equal to the "data" parameter in the "DataEvent" class
        message = event.data

        # unpickle the string
        pickled_dict = message.to_string()

        #separate the string into values for each text control (attrs is
a pickle object)
        attrs = pickle.loads(pickled_dict)

        #pass this pickle object into update
        self.update(attrs)


The purpose of getting the pickle in file is so that i can make a little
program to resend it to this program at will for testing purposes.
Clearly I was not aware that we cant put pickled data into a test file.
 What would be the best way to save the pickle for testing purposes?






More information about the Tutor mailing list