在Python中,dump
函數通常用于將數據結構(如列表、字典等)序列化為特定格式的文件。以下是一些常見的序列化方法及其對應的dump
函數:
json.dump()
import json
data = {
"name": "John",
"age": 30,
"city": "New York"
}
with open("data.json", "w") as write_file:
json.dump(data, write_file)
pickle.dump()
import pickle
data = {
"name": "John",
"age": 30,
"city": "New York"
}
with open("data.pkl", "wb") as write_file:
pickle.dump(data, write_file)
yaml.dump()
(需要安裝PyYAML庫)import yaml
data = {
"name": "John",
"age": 30,
"city": "New York"
}
with open("data.yaml", "w") as write_file:
yaml.dump(data, write_file)
注意:在使用這些函數時,請確保已經正確安裝了相應的庫。例如,要使用YAML,需要先運行pip install pyyaml
。