[Tutor] Need help printing a pickled data

Alan Gauld alan.gauld at btinternet.com
Tue Jun 25 01:17:58 CEST 2013


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.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list