pickle_example.py
· 439 B · Python
Raw
import pickle
# 定義要序列化的物件(字典)
data = {
"name": "Timmy",
"age": 30,
"skills": ["Python", "Docker", "JavaScript"]
}
# 將物件序列化並存入檔案
with open("data.pkl", "wb") as file:
pickle.dump(data, file)
print("物件已存入 data.pkl")
# 從檔案反序列化讀取物件
with open("data.pkl", "rb") as file:
loaded_data = pickle.load(file)
print("讀取的物件:", loaded_data)
| 1 | import pickle |
| 2 | |
| 3 | # 定義要序列化的物件(字典) |
| 4 | data = { |
| 5 | "name": "Timmy", |
| 6 | "age": 30, |
| 7 | "skills": ["Python", "Docker", "JavaScript"] |
| 8 | } |
| 9 | |
| 10 | # 將物件序列化並存入檔案 |
| 11 | with open("data.pkl", "wb") as file: |
| 12 | pickle.dump(data, file) |
| 13 | print("物件已存入 data.pkl") |
| 14 | |
| 15 | # 從檔案反序列化讀取物件 |
| 16 | with open("data.pkl", "rb") as file: |
| 17 | loaded_data = pickle.load(file) |
| 18 | |
| 19 | print("讀取的物件:", loaded_data) |
| 20 |