You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3 Jupyter Notebook中使用pickle.load()加载pickle文件时遇TypeError

Fix for TypeError: a bytes-like object is required, not 'str' when loading pickle files

The problem here is that you’re opening the pickle file in text mode ("r"), but pickle.load() expects a file stream in binary format. Pickle serializes data into raw bytes, so reading it as text will cause this mismatch error.

Here’s the corrected code to resolve the issue:

import pickle  # Ensure you've imported the pickle module first!

with open("/home/amit/Downloads/may2_18_company_data_with_cluster.pickle", "rb") as f:
    c = pickle.load(f)

Key adjustments made:

  • Swapped "r" (text read mode) for "rb" (binary read mode) – this tells Python to read the file as raw byte data instead of trying to decode it into text strings.
  • Removed the encoding='utf8' parameter, since binary mode doesn’t use text encoding (it works directly with bytes).

Why this fixes the error:

When you open a file in text mode, Python automatically converts bytes to strings in the background. Pickle, however, needs the original binary data to reconstruct your object. Using binary mode preserves the byte structure that pickle.load() expects.

As a quick bonus tip: when writing pickle files later, use "wb" (binary write mode) to ensure you’re saving data in the correct format:

with open("output_data.pickle", "wb") as f:
    pickle.dump(your_object, f)

内容的提问来源于stack exchange,提问作者Amit Pratap

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:18:49