0

While I was trying to create a way to save data using pickle, I ran into a local variable being referenced before assignment error.

CurrentDirectory = os.getcwd()#Finds current working directory
SaveDirectory = CurrentDirectory + "\Saves" #Save Directory for files
SaveDataList = [Name,Other]

logger.debug("It appears that all values were created successfully")

#Create new save
def MakeNewSave():
    logger.debug("Preparing to create new save file under name 'save.p'.")
    if not(os.path.exists(SaveDirectory)):
        os.makedirs(SaveDirectory)
    os.chdir(SaveDirectory)
    pickle.dump( SaveDataList, open("saves.p","wb"))
    logger.debug("Save file was made.")
    logger.debug("Load SaveDataList")
    SaveDataList = pickle.load( open("saves.p","wb"))
    logger.debug("Printing done message to screen.")
    print("Done.")

#Main

def main():

    CurrentDate= time.strftime("%d/%m/%Y")

    CheckForSave = os.path.isfile(SaveDirectory + "\saves.p") #Checks for saves
    logger.debug("Checked for save file, status:")
    logger.debug(CheckForSave)
    PromptSyntaxInfo = input("This program only accepts 'y/n', followed by enter on inputs where only two choices are availible. Exceptions will be explained on said prompts.")
    if (CheckForSave == True):
        logger.debug("Ask User for choice on loading save file.")
        UserSave = input("Save file was found. Load? y/n")
        if (UserSave == 'y'):
            logger.debug("Attempting to load data.")
            os.chdir(SaveDirectory)
            SaveDataList = pickle.load( open("saves.p", "rb"))
            UserConfirm = input("Done, press ENTER to continue")
            logger.debug("Data load complete.")
        else:
            logger.debug("User chose not to load save file.")

    else:
        logger.debug("No save file found. Preparing to create a save file.")
        print("No save file found. Creating new save file.")
        SaveStatus = MakeNewSave()
        logger.debug("MakeNewSave done.")

    print("No save file was found. Making new save file")


main()

Traceback:

Traceback (most recent call last):
  File "D:\PythonFiles\Attempt2\SaveFile.py", line 76, in <module>
    main()
  File "D:\PythonFiles\Attempt2\SaveFile.py", line 70, in main
    SaveStatus = MakeNewSave()
  File "D:\PythonFiles\Attempt2\SaveFile.py", line 38, in MakeNewSave
    pickle.dump( SaveDataList, open("saves.p","wb"))
UnboundLocalError: local variable 'SaveDataList' referenced before assignment

But since it happens inside of the arguments for a pickle function, I am not sure how to handle this. Any advice? Thanks.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
John
  • 3
  • 2
  • Please include the full traceback, don't leave us guessing where the exception was thrown or how Python got there. – Martijn Pieters May 28 '17 at 22:30
  • You assign to `SaveDataList` in the function, so it is considered a *local name*. You can't access that name until you assigned to it. Did you want it to be a global instead? Then make it one with a `global SaveDataList` statement at the top of the function. – Martijn Pieters May 28 '17 at 22:31
  • @MartijnPieters Sorry about that, I am new to this site and I had not read the articles in help center completely yet. Is this the information you were looking for? – John May 29 '17 at 00:18
  • That was indeed the info I was looking for. Your question was answered before, see the duplicate. – Martijn Pieters May 29 '17 at 07:59
  • The article was helpful, thanks. – John May 29 '17 at 15:43

0 Answers0