为什么 except 不能捕获 FileNotFound 错误 python

问题描述 投票:0回答:1

我正在尝试创建一个文件并使用“x”(与 open 一起使用)读取其中的内容,然后我包围了一个尝试并抓住了它。但是,即使有 except ,它似乎也不起作用。我什至把具体的错误放在那里。

try:
    with open("apikey.txt", "x") as f:
        ...
except FileExistsError:
    with open("apikey.txt", "r") as f:
       ...
python file-handling try-except
1个回答
0
投票

信息有限。也许您在 except 语句中使用了错误的错误。 试试这个来测试:

try:
    with open("apikey.txt", "x") as f:
        ...
except:
    with open("apikey.txt", "r") as f:
       ...
© www.soinside.com 2019 - 2024. All rights reserved.