gpt4 book ai didi

python - 如何在Python中读取和使用pickled文件?

转载 作者:太空宇宙 更新时间:2023-11-03 18:24:57 26 4
gpt4 key购买 nike

我正在Python 3.4.0中制作一个文本RPG,并且正在制作保存数据。我的程序可以创建该文件,但是当它尝试读取该文件时,它只读取第一行。
如何制作该程序以便它单独读取这些行以及如何在我的程序中使用这些行?

import os.path     
import time
import pickle

save_data = open("Text_RPG_save_data.dat", "wb")
load_data = open("Text_RPG_save_data.dat", "rb")

def data_save():
print("Saving progress...")
user_name = input("Enter your username.")
level = str(0)
pickle.dump("user_name = " + user_name, save_data)
pickle.dump("\nlevel = " + level, save_data)
save_data.close()
print("Save successful.")


def data_load():
print("Loading progress...")
loaded_data = pickle.load(load_data)
print(loaded_data)
load_data.close()
print("Load successful.")

def data_delete():
os.remove("Text_RPG_save_data.dat")

data_save()
data_load()

delete_affirm = input("Would you like to delete your progress? Y/N")
if delete_affirm == "Y":
data_delete()
time.sleep(5)
if delete_affirm == "N":
time.sleep(5)

当前结果:

Loading progress...
user_name = Foo
Load successful.

预期结果:

Loading progress...
Welcome, Foo! You are currently level 0.
Load successful.

最佳答案

"""
Text RPG, by user3587526
2014-04-30 v0.1
2014-11-12 v0.2 Save/load multiple player values in dictionary.
"""

import os.path
import time
import pickle

def data_save():
player = {}
player['name'] = input("Enter your username: ")
player['level'] = 0
print("Saving progress...")
with open("Text_RPG_save_data.dat", "wb") as f:
pickle.dump(player, f)
print("Save successful.")

def data_load():
print("Loading progress...")
with open("Text_RPG_save_data.dat", "rb") as f:
player = pickle.load(f)
print("Welcome, %s! You are currently level %s." % (player['name'], player['level']))
print("Load successful.")

def data_delete():
os.remove("Text_RPG_save_data.dat")

data_save()
data_load()

delete_affirm = input("Would you like to delete your progress? (Y/N)").upper()
if delete_affirm == "Y":
data_delete()
time.sleep(5)
if delete_affirm == "N":
time.sleep(5)

输出:

Enter your username: Foo
Saving progress...
Save successful.
Loading progress...
Welcome, Foo! You are currently level 0.
Load successful.
Would you like to delete your progress? (Y/N)y

关于python - 如何在Python中读取和使用pickled文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23378961/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com