You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pygame中保存数据?实现变量跨代码运行留存

实现Python变量跨运行留存的解决方案

要让变量a的值在代码多次运行之间留存,核心是把变量值持久化存储到本地文件中,下次运行时先读取文件里的保存值,再进行逻辑操作。以下是三种简单可行的实现方案:

方法1:使用普通文本文件存储

这种方法最直观,适合存储单个简单变量:

# 读取保存的数值,首次运行文件不存在则初始化为1
try:
    with open("points.txt", "r") as f:
        a = int(f.read().strip())
except FileNotFoundError:
    a = 1

b = input("c or d: ")
if b == "c":
    a += 1
    print(f"you have {a} points")
elif b == "d":
    a -= 1
    print(f"you have {a} points")

# 将更新后的数值写入文件,覆盖原有内容
with open("points.txt", "w") as f:
    f.write(str(a))

运行后,项目根目录会生成points.txt文件,每次运行都会读取其中的数值,修改后再保存。

方法2:使用JSON文件存储

JSON格式更规范,适合后续扩展存储更多数据:

import json

# 读取或初始化数值
try:
    with open("points.json", "r") as f:
        data = json.load(f)
        a = data.get("points", 1)
except (FileNotFoundError, json.JSONDecodeError):
    a = 1

b = input("c or d: ")
if b == "c":
    a += 1
    print(f"you have {a} points")
elif b == "d":
    a -= 1
    print(f"you have {a} points")

# 保存为JSON格式
with open("points.json", "w") as f:
    json.dump({"points": a}, f)

方法3:使用Pickle序列化存储

Pickle可以直接序列化Python对象,适合存储复杂数据类型,单个变量也适用:

import pickle

# 读取或初始化数值
try:
    with open("points.pkl", "rb") as f:
        a = pickle.load(f)
except (FileNotFoundError, pickle.UnpicklingError):
    a = 1

b = input("c or d: ")
if b == "c":
    a += 1
    print(f"you have {a} points")
elif b == "d":
    a -= 1
    print(f"you have {a} points")

# 序列化保存变量
with open("points.pkl", "wb") as f:
    pickle.dump(a, f)

注意事项

  • 存储文件会自动生成在PyCharm项目的根目录下
  • 如果存储文件被意外删除,变量会回到初始值1
  • 若输入非"c"或"d",变量值保持不变并继续留存

内容的提问来源于stack exchange,提问作者ItorYmovId

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 19:20:32