Sch*_*ote 2 python windows file-io python-3.x
我正在努力让我的游戏项目不能像1995年那样保存在自己的目录中.
标准库不合作.
基本上,我试图保存%appdata%\MYGAMENAME\(这是win32上的_savedir的值.)open()如果这样的文件夹不存在将变得可以理解,所以我用os.path.exists()它来检查它是否确实存在并创建它,如果它不存在.
麻烦的是,os.path.exists()返回True,但我可以查看文件夹并确认它没有.如果我在REPL中尝试它也不会返回True; 只在这里(我已经确认我的调试器确实如此).
酸洗步骤似乎正常进行; 它会else:立即跳到该条款.但我可以通过OS文件系统浏览器和REPL确认文件夹和文件都不存在!
这是完整的功能源(不要笑!):
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
Run Code Online (Sandbox Code Playgroud)
(是的,捕捉Exception通常是不可取的,但是如果出现任何问题,我希望事情能够优雅地失败,没有任何情况会出现真正的异常并且我想做其他任何事情.)
这可能是什么问题?
Python没有扩展它的价值%appdata%.而是相对于当前工作目录创建文字目录.运行print(os.path.abspath(_savedir)),即文件创建和存在的位置.
使用os.environ['APPDATA']创建的应用程序数据目录的绝对路径:
_savedir = os.path.join(os.environ['APPDATA'], 'MYGAMENAME')
Run Code Online (Sandbox Code Playgroud)