溫馨提示×

如何正確調(diào)用python的dump函數(shù)

小樊
82
2024-09-14 06:33:33
欄目: 編程語言

pickle.dump() 是 Python 中的一個(gè)函數(shù),用于將對象序列化為二進(jìn)制數(shù)據(jù)流

  1. 導(dǎo)入 pickle 模塊:
import pickle
  1. 創(chuàng)建一個(gè)需要序列化的對象。例如,我們可以創(chuàng)建一個(gè)字典:
data = {
    "name": "John",
    "age": 30,
    "city": "New York"
}
  1. 使用 open() 函數(shù)以二進(jìn)制寫模式('wb')打開一個(gè)文件,用于存儲(chǔ)序列化后的數(shù)據(jù):
with open("data_file.pkl", "wb") as file:
  1. 在上一步打開的文件中調(diào)用 pickle.dump() 函數(shù),將對象序列化并寫入文件:
    pickle.dump(data, file)

將這些代碼片段組合在一起,完整示例如下:

import pickle

data = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

with open("data_file.pkl", "wb") as file:
    pickle.dump(data, file)

此代碼將創(chuàng)建一個(gè)名為 data_file.pkl 的文件,其中包含序列化后的字典數(shù)據(jù)。

0