[Tutor] Need help printing a pickled data

Peter Otten __peter__ at web.de
Tue Jun 25 08:04:20 CEST 2013


Matt D wrote:

> 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 ;

No, you aren't listening to Alan. The suggestive filename notwithstanding

>         with open('mypicklelog.txt','a') as log:
>             log.write(self.data)

will fail unless self.data is a string. Disregarding all other problems for 
the moment, you need

with open('mypicklelog.txt','ab') as log: # open in binary mode
    pickle.dump(self.data, log) # serialize data and write to file

where pickle.dump(obj, file) converts `obj` to a sequence of bytes before it 
is written to `file`.



More information about the Tutor mailing list