[Tutor] Need help printing a pickled data
Steven D'Aprano
steve at pearwood.info
Wed Jun 26 03:12:39 CEST 2013
On 26/06/13 04:30, Matt D wrote:
> On 06/25/2013 01:54 PM, Alan Gauld wrote:
>> On 25/06/13 17:32, Matt D wrote:
>>
>>> self.data = data
>>> with open('mypicklelog.txt','ab') as log: # open in binary mode
>>> pickle.dump(self.data, log) # serialize data and write to
>>> file
>>>
>>>
>>> And I still get nothing.
>>
>> Define 'nothing'.
>>
>> Does the file exist?
>> Does it have anything in it?
>> Does self.data exist - what does it look like if you print it?
>> Are there any error messages?
>>
> Yeh nothing as in an empty file. The file is there but there is nothing
> written in it. self.data exists. that the problem if have is printing
> what is in it so i dont know what it looks like. No error messages
> currently in the terminal.
The obvious test is to confirm that you can see other output written to the log file.
self.data = data
with open('mypicklelog.txt','ab') as log: # open in binary mode
log.write('before\n')
pickle.dump(self.data, log)
log.write('after\n')
I still think it is silly to write pickled data to a log. Logs are for human-readable information, not arbitrary data. Even with text-mode pickle, it's still junk:
py> import pickle
py> data = {'a': None, 'b': 42}
py> pickle.dumps(data, 0)
"(dp0\nS'a'\np1\nNsS'b'\np2\nI42\ns."
Why do you want to see rubbish like that inside your log file? Surely something like this is better?
log.write("data = %r" % data)
which will give you a line like this:
data = {'a': None, 'b': 42}
in your log, which is a million times more understandable than a pickle.
--
Steven
More information about the Tutor
mailing list