Python Pickle UnboundLocalError

时间:2017-05-28 22:29:21

标签: python-3.x pickle

当我尝试使用pickle创建一种保存数据的方法时,我遇到了在赋值错误之前被引用的局部变量。

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

但是因为它发生在pickle函数的参数内部,所以我不知道如何处理它。有什么建议?感谢。

0 个答案:

没有答案