在Python中,pickle.dump()
函數(shù)用于將對象序列化為二進(jìn)制數(shù)據(jù)流
with open()
語句打開文件:這樣可以確保文件在操作完成后正確關(guān)閉。pickle.dump()
函數(shù)將對象序列化到文件中。pickle.load()
函數(shù)從文件中反序列化對象。示例代碼:
import pickle
# 要序列化的對象
data = {
"name": "John",
"age": 30,
"city": "New York"
}
# 將對象序列化到文件中
with open("data.pkl", "wb") as file:
pickle.dump(data, file)
# 從文件中反序列化對象
with open("data.pkl", "rb") as file:
loaded_data = pickle.load(file)
print(loaded_data)
注意:當(dāng)使用pickle
模塊時,請確保只反序列化來自可信來源的數(shù)據(jù),因為pickle
模塊可能存在安全風(fēng)險。如果可能,請考慮使用其他序列化庫,如json
或yaml
。