473,395 Members | 1,968 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

pickle, cPickle, & HIGHEST_PROTOCOL

I wonder if someone can explain what is wrong here. I am pickling a
list of dictionaries (see code attached) and unpickling it back using
the HIGHEST_PROTOCOL of pickle and cPickle. I am getting an error
message and trace backs if the list exceeds eight items. Whether I use
pickle or cPickle does not matter, i.e., the eight number causes a
problem in both modules, although the trace backs are of course
dissimilar.

This pickling and unpickling of the list of dictionaries worked when I
stopped using the HIGHEST_PROTOCOL in both modules (pickle and
cPickle), which got Python to use the ASCII format (I suppose) as I can
read the pickled data.

This behavior was observed in Python 2.3.4 (final), and 2.4 (final) on
Win98.

Any comments?
Regards,
Khalid

# Sample program tester.py begin
!
! import pickle as pkl
! import os
! #-----------------------------
! def test_pickle():
! fn = 'rkeys.txt'
! f = file(fn, 'r')
! lines = f.readlines()
! f.close()
! _test_list = []
! for line in lines:
! sline = line.split(',')
! #print sline
! key, value = sline[0], sline[1].strip()
! _test_dict = {}
! _test_dict[key] = value
! _test_list.append(_test_dict)
!
! # Let's see the contents of our object
! print _test_list
!
! # Then pickle it
! f = file('pkl_' + fn, 'w')
! pkl.dump(_test_list, f, pkl.HIGHEST_PROTOCOL)
! f.close()
!
! # Empty it
! _test_list = []
! print _test_list
!
! # Unpickling object here:
! f = file('pkl_' + fn, 'r')
! _test_list = pkl.load(f)
! f.close()
!
! # See contents after loading
! print _test_list
!#-----------------------------
!if __name__ == '__main__':
! test_pickle()
!
!# Sample program end
# Contents of file rkeys.txt (without the triple quotes):
"""
'1','v1'
'2','v2'
'3','v3'
'4','v4'
'5','v5'
'6','v6'
'7','v7'
'8','v8'
'9','v9'
"""
# Output (without the triple quotes)
# Using "import pickle as pkl":
"""
[{"'1'": "'v1'"}, {"'2'": "'v2'"}, {"'3'": "'v3'"}, {"'4'": "'v4'"},
{"'5'": "'v5'"}, {"'6'": "'v6'"}, {"'7'": "'v7'"}, {"'8'": "'v8'"},
{"'9'": "'v9'"}]
[]
!Traceback (most recent call last):
! File "tester.py", line 41, in ?
! test_pickle()
! File "tester.py", line 34, in test_pickle
! _test_list = pkl.load(f)
! File "D:\PY23\PYTHON\DIST\SRC\lib\pickle.py", line 1390, in load
! return Unpickler(file).load()
! File "D:\PY23\PYTHON\DIST\SRC\lib\pickle.py", line 872, in load
! dispatch[key](self)
! File "D:\PY23\PYTHON\DIST\SRC\lib\pickle.py", line 1189, in
load_binput
! i = ord(self.read(1))
!TypeError: ord() expected a character, but string of length 0 found
"""
# Output (without the triple quotes)
# Using "import cPickle as pkl":
"""
[{"'1'": "'v1'"}, {"'2'": "'v2'"}, {"'3'": "'v3'"}, {"'4'": "'v4'"},
{"'5'": "'v5'"}, {"'6'": "'v6'"}, {"'7'": "'v7'"}, {"'8'": "'v8'"},
{"'9'": "'v9'"}]
[]
!Traceback (most recent call last):
! File "tester.py", line 41, in ?
! test_pickle()
! File "tester.py", line 34, in test_pickle
! _test_list = pkl.load(f)
!EOFError
"""
# Output (without the triple quotes)
# Using "import cPickle as pkl", or "import pickle as pkl"
# but _not_ using the HIGHEST_PROTOCOL:
"""
[{"'1'": "'v1'"}, {"'2'": "'v2'"}, {"'3'": "'v3'"}, {"'4'": "'v4'"},
{"'5'": "'v5'"}, {"'6'": "'v6'"}, {"'7'": "'v7'"}, {"'8'": "'v8'"},
{"'9'": "'v9'"}]
[]
[{"'1'": "'v1'"}, {"'2'": "'v2'"}, {"'3'": "'v3'"}, {"'4'": "'v4'"},
{"'5'": "'v5'"}, {"'6'": "'v6'"}, {"'7'": "'v7'"}, {"'8'": "'v8'"},
{"'9'": "'v9'"}]
"""

Jul 18 '05 #1
1 3481
[A.B., Khalid]
I wonder if someone can explain what is wrong here. I am pickling a
list of dictionaries (see code attached) and unpickling it back using
the HIGHEST_PROTOCOL of pickle and cPickle. .... ... on Win98.


Pickles are binary data. Therefore you should open pickle files in
binary mode on all platforms, and must open them in binary mode on
Windows. That is, replace your lines:

f = file('pkl_' + fn, 'w')
f = file('pkl_' + fn, 'r')

with:

f = file('pkl_' + fn, 'wb')
f = file('pkl_' + fn, 'rb')

It's true that you can get away with opening pickle files in text mode
on Windows if you stick to the default pickle protocol (0), although
in that case your pickle files won't be portable across platforms.
For that reason, don't try to be clever: always use binary-mode files
to store pickles, regardless of pickle protocol in use.
Jul 18 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Guenter Walser | last post by:
Hello, When using the codeline: pickle.dump(self, file, pickle.HIGHEST_PROTOCOL) my program runs perfectly fine: --------------------------- Testprotocol -----------------------------
1
by: Jesse Bloom | last post by:
I keep running into a problem when I use pickle or cPickle to unpickle a python object I have serialized from the database. I read the string for the serialized object. Apparently I am missing an...
3
by: Michael Hohn | last post by:
Hi, under python 2.2, the pickle/unpickle sequence incorrectly restores a larger data structure I have. Under Python 2.3, these structures now give an explicit exception from...
8
by: Hans Georg Krauthaeuser | last post by:
Dear all, I have a long running application (electromagnetic compatibility measurements in mode-stirred chambers over GPIB) that use pickle (cPickle) to autosave a class instance with all the...
1
by: Philippe C. Martin | last post by:
Hi, How would one go about extracting the pickle module from Python (ex: to make a .a or a .dll) ? Thanks Philippe
2
by: Boris Borcic | last post by:
Assuming that the items of my_stream share no content (they are dumps of db cursor fetches), is there a simple way to do the equivalent of def pickles(my_stream) : from cPickle import...
8
by: Victor Kryukov | last post by:
Hello list, I've found the following strange behavior of cPickle. Do you think it's a bug, or is it by design? Best regards, Victor. from pickle import dumps from cPickle import dumps as...
2
by: Victor Lin | last post by:
Hi, I encounter a problem with pickle. I download a html from: ...
1
by: Nagu | last post by:
I didn't have the problem with dumping as a string. When I tried to save this object to a file, memory error pops up. I am sorry for the mention of size for a dictionary. What I meant by...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.