python 字典dict 保存和读取

在 Python 里把 dict 保存成文件以及恢复有几种常见方式,取决于你想保存的格式和用途:


方法一:使用 json(推荐,可读性强,跨语言通用)

import json

# 要保存的字典
data = {"name": "Alice", "age": 25, "hobbies": ["reading", "gaming"]}

# 保存到文件
with open("data.json", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False, indent=4)

# 从文件恢复
with open("data.json", "r", encoding="utf-8") as f:
    restored_data = json.load(f)

print(restored_data)

优点:可读性好,文件可跨语言解析。
缺点:不支持 Python 特有的对象(如 set、自定义类)。


方法二:使用 pickle(Python 专用)

import pickle

data = {"name": "Alice", "age": 25, "hobbies": ["reading", "gaming"]}

# 保存到文件
with open("data.pkl", "wb") as f:
    pickle.dump(data, f)

# 从文件恢复
with open("data.pkl", "rb") as f:
    restored_data = pickle.load(f)

print(restored_data)

优点:几乎能序列化所有 Python 对象。
缺点:文件不可读,只能在 Python 中使用,并且存在安全风险(加载未知来源的 pickle 文件可能执行恶意代码)。


方法三:保存为 txtcsv(适合简单字典)

data = {"name": "Alice", "age": 25, "city": "Beijing"}

# 保存为 txt
with open("data.txt", "w", encoding="utf-8") as f:
    for k, v in data.items():
        f.write(f"{k}:{v}\n")

# 恢复
restored_data = {}
with open("data.txt", "r", encoding="utf-8") as f:
    for line in f:
        k, v = line.strip().split(":")
        restored_data[k] = v

print(restored_data)

👉 一般建议:

  • 如果要 跨语言/跨平台,用 json
  • 如果只是 在 Python 内部保存和恢复,且对象比较复杂,用 pickle

要不要我帮你写一个 支持任意 dict 的保存/恢复函数,可以一键选择 jsonpickle

posted @ 2025-09-03 12:48  X1OO  阅读(138)  评论(0)    收藏  举报