【问题标题】:How to make code do something if file isn't found in Python? [duplicate]如果在 Python 中找不到文件,如何使代码执行某些操作? [复制]
【发布时间】:2021-03-12 19:40:26
【问题描述】:

我想检查我正在开发的命令行游戏是否保存游戏。

游戏存档是单一的".txt" 文件,这段代码的工作方式是尝试打开"%appdata%\Roaming\AdventureChapt1\" 文件夹中的"name.txt" 文件,然后在Python 无法打开时查找错误消息找到文件。

我该怎么做?

print('Loading Save Data')

savecheck = open('%appdata%/Roaming/AdventureChapt1/name.txt', 'rt')

if savecheck.read() == '':
    newgame() # calls the "newgame" function to bring up the New Game wizard

【问题讨论】:

    标签: python error-handling file-handling


    【解决方案1】:

    您可以使用tryexcept

    try:
        with open('%appdata%/Roaming/AdventureChapt1/name.txt', 'rt') as savecheck:
            # code that reads saved game
    except FileNotFoundError:
        newgame()
    

    【讨论】:

      【解决方案2】:

      您可以使用多种方法来查看文件是否存在。
      我的口味是

      from os import path
      filepath = "path_to_file"
      if not path.exists(filepath):
          # do stuff when file doesn't exist
      

      参考:https://www.guru99.com/python-check-if-file-exists.html

      【讨论】:

        猜你喜欢
        • 2019-02-03
        • 1970-01-01
        • 2021-10-01
        • 1970-01-01
        • 2019-07-18
        • 2013-02-12
        • 2016-11-14
        • 2012-03-28
        • 1970-01-01
        相关资源
        最近更新 更多