加载泡菜文件会返回'could not find file with a name' (file_name),即使文件存在



我正在尝试加载程序最近为保存玩家角色创建的pickle文件。昨天它是工作的,但是现在,如果我输入一个现有文件的名称,它只是返回:'找不到一个名称的文件' (file_name)。我不知道我是否不小心改变了什么,但它会很好得到它排序。提前谢谢。

代码:

from pprint import pprint
import random
import math
import time
import datetime
import pickle
from os import system
def w(t):
time.sleep(t)
def pickle_load():
while True:
save_game_name = input('n > character file name: ')
try:
print('n > loading character...')
w(1)
pickle_in = open(save_game_load,"rb")
character_save = pickle.load(pickle_in)
print(' > character loaded successfully')
w(0.3)
print('n > welcome back',character_save['name'],'!')
print(' > here are your stats from last time: ')
print('n >',character_save)
break
except:
print(' > could not find a file with name',save_game_name)
def version_counter(filename="adventure_colussus_version_counter.dat"):
with open(filename, "a+") as f:
f.seek(0)
val = int(f.read() or 0) + 1
f.seek(0)
f.truncate()
f.write(str(val))
return val
counter = version_counter()
class hero:
def __init__(self, Hhealth, Hattack, Hluck, Hranged, Hdefence, Hmagic, Hname):
self.health = Hhealth
self.attack = Hattack
self.luck = Hluck
self.ranged = Hranged
self.defence = Hdefence
self.magic = Hmagic
self.name = Hname
def getHealth(self):
return self.health
def getAttack(self):
return self.attack
def getLuck(self):
return self.luck
def getRanged(self):
return self.ranged
def getDefence(self):
return self.defence
def getMagic(self):
return self.magic
def getName(self):
return self.name
def setHealth(self, newHealth):
self.health = newHealth
def setAttack(self, newAttack):
self.attack = newAttack
def setLuck(self, newLuck):
self.luck = newLuck
def setRanged(self, newRanged):
self.ranged = newRanged
def setDefence(self, newDefence):
self.defence = newDefence
def setMagic(self, newMagic):
self.magic = newMagic
def setName(self, newName):
self.name = newName
def create_character():
print('n > do you prefer to play more strategically[1] or more like a warrior[2]? ')
q1 = input(' > ')
while q1 != '1' and q1 != '2':
print('n > do you prefer to play more strategically[1] or more like a warrior[2]? ')
q1 = input(' > ')
#a more strategic approach
if q1 == '1':
heroAttack = 50
heroDefence = 100
#a more warrior approach
elif q1 == '2':
heroAttack = 100
heroDefence = 50
print('n > do you prefer using a bow and arrow[1] or magic[2]? ')
q3 = input(' > ')
while q3 != '1' and q3 != '2':
print('n > do you prefer using a bow and arrow[1] or magic[2]? ')
q3 = input(' > ')
#a more strategic approach
if q3 == '1':
heroRanged = 100
heroMagic = 50
#a more warrior approach
elif q3 == '2':
heroRanged = 50
heroMagic = 100
q2 = input('n > press enter to roll a dice...')
w(0.3)
print(' > rolling dice...')
heroLuck = random.randint(0,10)
print(' > your hero has',heroLuck,'luck out of 10')
heroName = input('n > what should you hero be named? ')
w(0.3)
print(' > welcome! your mighty hero shall be named:',heroName,'!!!')
return (heroAttack, heroLuck, heroRanged, heroDefence, heroMagic, heroName)

class enemy:
def __init__(self, Ehealth, Eattack, Eluck, Eranged, Edefence, Emagic, Ename):
self.health = Ehealth
self.attack = Eattack
self.luck = Eluck
self.ranged = Eranged
self.defence = Edefence
self.magic = Emagic
self.name = Ename
def egetHealth(self):
return self.health
def egetAttack(self):
return self.attack
def egetLuck(self):
return self.luck
def egetRanged(self):
return self.ranged
def egetDefence(self):
return self.defence
def egetMagic(self):
return self.magic
def egetName(self):
return self.name
def esetHealth(self, newHealth):
self.health = newHealth
def esetAttack(self, newAttack):
self.attack = newAttack
def esetLuck(self, newLuck):
self.luck = newLuck
def esetRanged(self, newRanged):
self.ranged = newRanged
def esetDefence(self, newDefence):
self.defence = newDefence
def esetMagic(self, newMagic):
self.magic = newMagic
def esetName(self, newName):
self.name = newName
def opening():
w(0.5)
e = datetime.datetime.now()
print(' _____________________________________________________________________________________________________________________')
print('n  <Adventure Colussus>         version: v',counter,'| current date: ',e, '| date of creation: 9.2.2021')
print(' _____________________________________________________________________________________________________________________')
w(0.5)
print(r"""
/                       /                        /                       /
/**                     /**                      /**                     /**
/****   /      /      /****   /               /****   /      /      /****   /
/       /**    /      /       /**             /       /**    /      /       /**
/  /    /      /      /  /    /        /     /  /    /      /      /  /    /    
/  /    /      /      /  /    /        /     /  /    /      /      /  /    /      
/  /    / /           /  /    / /     /     /  /    / /           /  /    / /     
/  /      /  /       /  /      /  /        /  /      /  /       /  /      /  /   
__/__/_______/___/_______/__/_______/___/________/__/_______/___/_______/__/_______/___/______
""")
print(' _____________________________________________________________________________________________________________________')
print('n[1] create new game')
print('[2] load existing game')
choice = input("n > ")
if choice == '1':
print("n > you have chosen to create a new game: redirecting...")
w(0.75)
system('cls')
#Carry on with creating a new game here using pickle dump
print(' _____________________________________________________________________________________________________________________')
print('  n  we will begin with creating your character:                                        quick tip: choose wisely')
print(' _____________________________________________________________________________________________________________________')
w(0.75)
print(r"""
,;~;,                                                                ,;;,.
/_                                                              /~
(  /                                                             ([-])
(()      //)                                                   ,_.~~~.
| \  ,,;;'                                                 ()--|   ,
__ _(  )m=(((((((((((((================--------               ,_//   |   |>)
/'  ' '()/~' '.(, |                                         (~'  m''~)(   )/
,;(      )||     |  ~                                           (~||~)/ //~\
,;'     /-(.;,   )                                                 ||   ()   ()
,;'   ) /       ) /                                                  ||   ()   ()
//         ||                                                  ||   ||   ||
)_         )_                                                || ,;.)   (.;,
""")
print('n _____________________________________________________________________________________________________________________')
class_data = create_character()
character = hero(100, class_data[0], class_data[1], class_data[2], class_data[3], class_data[4], class_data[5])
w(0.3)
print('n > these are the stats that your character has aquired: ')
print(' >',vars(character))
character_save = {"health": 100, "attack": class_data[0], "luck": class_data[1], "ranged": class_data[2], "defence":  class_data[3], "magic": class_data[4], "name": class_data[5]}
print('n > we should now save your character if you want to come back to it later: ')
save_game_name1 = input(' > desired name of file: ')
save_game_name12 = save_game_name1 + '.pickle'
pickle_out = open(save_game_name12,"wb")
pickle.dump(character_save, pickle_out)
print('n> saving character...')
w(1)
print('> character saved successfully')
pickle_out.close()
elif choice == '2':
print("n > you have chosen to load an existing game: redirecting...")
w(0.75)
system('cls')
#Carry on with loading an existing game here using pickle load
w(0.75)
print(' _____________________________________________________________________________________________________________________')
print('  n  we will begin with choosing an existing character:                             quick tip: make sure it exists!')
print(' _____________________________________________________________________________________________________________________')
w(0.75)
print(r"""
,;~;,                                                                ,;;,.
/_                                                              /~
(  /                                                             ([-])
(()      //)                                                   ,_.~~~.
| \  ,,;;'                                                 ()--|   ,
__ _(  )m=(((((((((((((================-------               ,_//   |   |>)
/'  ' '()/~' '.(, |                                         (~'  m''~)(   )/
,;(      )||     |  ~                                           (~||~)/ //~\
,;'     /-(.;,   )                                                 ||   ()   ()
,;'   ) /       ) /                                                  ||   ()   ()
//         ||                                                  ||   ||   ||
)_         )_                                                || ,;.)   (.;,
""")
print('n _____________________________________________________________________________________________________________________')
pickle_load()
elif choice == 'credits':
pass
else:
print(' > incorrect response. please try again')

opening()

我在加载pickle文件之前不小心删除了save_game_load = save_game_name + '.pickle':pickle_in = open(save_game_load,"rb").

由于它在函数pickle_load()中被处理为异常,它没有给我任何关于问题所在的指标,这就是为什么我在运行程序时有点困惑,因为所有的pickle文件都在与主.py文件相同的文件夹和目录中。

感谢Uptal Dutt为我澄清。

相关内容

  • 没有找到相关文章

最新更新