简体   繁体   中英

Loading a pickle file returns 'could not find file with a name' (file_name) even when file exists

I am trying to load a pickle file that the program recently created for saving a player character. Yesterday it was working, however now if i enter the name of an existing file it just returns: 'could not find file with a name' (file_name). I dont know whether i accidentaly changed something, but it would be nice to get it sorted. Thanks in advance.

Code:

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()

I had accidentally deleted save_game_load = save_game_name + '.pickle' before loading the pickle file: pickle_in = open(save_game_load,"rb") .

As it was being handled as an exception in the function pickle_load() , it did not give me any indicators as to what the problem was which is why I was slightly confused when running the program, as all pickle files were in the same folder and directory as the main .py file.

Thanks for Uptal Dutt for clearing that up for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM