如何在python中阅读和使用pickle文件?

时间:2014-04-30 03:05:10

标签: python pickle

我在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.

1 个答案:

答案 0 :(得分:1)

"""
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