os.path.exists()在Windows上的%appdata%中给出误报

时间:2015-07-24 19:02:04

标签: python windows python-3.x file-io

我试图让我的游戏项目不能保存在自己的目录中,就像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

(是的,抓住Exception通常是不可取的,但是如果出现任何问题,我希望事情能够优雅地失败,那里不会出现真正的异常,我想要做其他事。)

这可能是什么问题?

1 个答案:

答案 0 :(得分:8)

Python不会扩展%appdata%的值。而是相对于当前工作目录创建文字目录。运行print(os.path.abspath(_savedir)),即文件的创建和存在位置。

使用os.environ['APPDATA']创建应用程序数据目录的绝对路径:

_savedir = os.path.join(os.environ['APPDATA'], 'MYGAMENAME')