我试图让我的游戏项目不保存在自己的目录,就像是1995年的东西。
标准库不合作。
基本上,我试图保存在%appdata%\MYGAMENAME\
(这是win32上_savedir的值。)如果这样的文件夹不存在, open()
将变得可以理解,所以我使用os.path.exists()
检查它是否确实存在,如果不存在则创build它。
麻烦的是, os.path.exists()
返回True,但是我可以查看文件夹并确认它没有。 如果我在REPL中尝试它,它也不会返回True; 只有在这里(我已经用我的debugging器确认它)。
酸洗步骤似乎正常进行; 它会立即跳转到else:
子句。 但是我可以用操作系统文件系统浏览器和REPL确认文件夹和文件都不存在!
这里是全function的源代码(不要笑!):
def save(self): "Save the game." #Eh, ____ it, just pickle gamestate. What could go wrong? save_path=os.path.join(_savedir,"save.sav") temporary_save_path=os.path.join(_savedir,"new_save.sav") #Basically, we save to a temporary save, then if we succeed we copy it over the old one. #If anything goes wrong, we just give up and the old save is untouched. Either way we delete the temp save. if not os.path.exists(_savedir): print("Creating",_savedir) os.makedirs(_savedir) else: print(_savedir,"exists!") try: pickle.dump(self,open(temporary_save_path,"wb"),protocol=pickle.HIGHEST_PROTOCOL) except Exception as e: print("Save failed: {0}".format(e)) print("The game can continue, and your previous save is still intact.") else: shutil.move(temporary_save_path,save_path) finally: try: os.remove(temporary_save_path) except Exception: pass
(是的,捕捉Exception
通常是不可取的,但是如果出现任何错误,我希望事情能够优雅地失败,没有什么情况会出现一个实际的exception,而且我还想做其他任何事情。)
这里可能是什么问题?
Python不扩展%appdata%
的值。 而是相对于当前工作目录创建一个文字目录。 运行print(os.path.abspath(_savedir))
,这是文件的创建和存在位置。
使用os.environ['APPDATA']
创建应用程序数据目录的绝对路径:
_savedir = os.path.join(os.environ['APPDATA'], 'MYGAMENAME')