Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of pickle.dump in Python

I'm trying to learn how to use the pickle module in Python:

import pickle x = 123 f = open('data.txt','w') pickle.dump(x,f) 

Here's what I get:

Traceback (most recent call last):   File "D:\python\test.py", line 5, in <module>     pickle.dump(x,f) TypeError: must be str, not bytes 

However, this code works just fine:

import pickle dump = pickle.dump(123) print(dump) 


What am I doing wrong?

like image 416
Sergey Avatar asked Jan 02 '12 17:01

Sergey


People also ask

What is the use of pickle dump in Python?

Python Pickle dump dump() function to store the object data to the file. pickle. dump() function takes 3 arguments. The first argument is the object that you want to store.

What is the advantage of pickle Python?

The advantage of using pickle is that it can serialize pretty much any Python object, without having to add any extra code. Its also smart in that in will only write out any single object once, making it effective to store recursive structures like graphs.

How do I dump a pickle file?

First, import pickle to use it, then we define an example dictionary, which is a Python object. Next, we open a file (note that we open to write bytes in Python 3+), then we use pickle. dump() to put the dict into opened file, then close. Use pickle.

What is pickling and Unpickling What is the purpose of dump function?

“Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation, whereby a byte stream (from a binary file or bytes-like object) is converted back into an object hierarchy.


2 Answers

The problem is that you're opening the file in text mode. You need to use binary here:

>>> f = open('data.txt','w') >>> pickle.dump(123,f) Traceback (most recent call last):   File "<stdin>", line 1, in <module> TypeError: must be str, not bytes >>>  >>> f = open('data.txt','wb') >>> pickle.dump(123,f) >>>  
like image 97
DSM Avatar answered Oct 03 '22 18:10

DSM


The write method for file-like objects, only accept a single string argument. The dumps method in the pickle module automatically casts arguments as strings, whereas the the dump method will write a pickled representation of the object to the open file. Since 123 is not a string it throws the TypeError error.

This is acknowledged in pickle.dump documentation.

like image 21
garnertb Avatar answered Oct 03 '22 20:10

garnertb