Using pickle.dump - TypeError must be str, not bytes
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
The error TypeError: must be str, not bytes when using pickle.dump() means you opened the file in text mode ('w') instead of binary mode ('wb'). Pickle serializes Python objects to a byte stream, so the output file must be opened in binary mode. This is a Python 3 issue — Python 2 allowed text mode for pickle because it did not distinguish between str and bytes.
The Error
pickle.dump() writes bytes, but the file opened with 'w' expects strings. The fix is one character.
The Fix
The b in 'wb' and 'rb' tells Python to handle the file as binary (bytes), not text (strings).
File Mode Reference
| Mode | Type | Use |
'w' | Text (str) | Writing text files (.txt, .csv) |
'wb' | Binary (bytes) | Writing pickle, images, protobuf |
'r' | Text (str) | Reading text files |
'rb' | Binary (bytes) | Reading pickle, images |
'ab' | Binary append | Appending to binary files |
Same Error with pickle.dumps() to File
Using pickle with io.BytesIO
For in-memory binary streams:
pickle requires BytesIO, not StringIO.
Multiple Objects in One File
Pickle Protocol Versions
Higher protocols are faster and support more types but are not backward-compatible.
Alternatives to Pickle
Python 2 vs Python 3
When migrating Python 2 code to Python 3, add b to every open() call used with pickle.
Common Pitfalls
- Forgetting
'b'in the file mode: The most common cause.'w'vs'wb'is a single character difference that causes the error. Always use'wb'for writing and'rb'for reading pickle files. - Using
open()without context manager:f = open('data.pkl', 'wb')withoutwithrisks leaving the file open on exceptions. Always usewith open(...) as f:. - Mixing
pickle.dumpandpickle.dumps:dump()writes to a file object.dumps()returns bytes. Usingdumps()and then writing to a text file causes the same error. - Security risk:
pickle.load()can execute arbitrary code. Never unpickle data from untrusted sources. Usejsonfor data from external systems. - Loading pickle across Python versions: Pickles created with a higher protocol cannot be loaded by older Python versions. Specify
protocol=2for maximum compatibility.
Summary
- Open files in binary mode (
'wb'/'rb') for pickle —'w'/'r'causesTypeError pickle.dump(obj, file)writes to a binary file;pickle.dumps(obj)returns bytes- Use
io.BytesIOfor in-memory pickle operations, notio.StringIO - Use
jsoninstead of pickle when you need human-readable or cross-language serialization - Never
pickle.load()untrusted data — it can execute arbitrary code - Specify
protocol=2when sharing pickles across Python versions

