Python - 除了(FileNotFoundError)之外的 open() ?

ala*_*ljs 9 python python-3.x

我觉得很奇怪

with open(file, 'r')
Run Code Online (Sandbox Code Playgroud)

可以举报

FileNotFoundError: [Errno 2]
Run Code Online (Sandbox Code Playgroud)

但我无法以某种方式捕捉到并继续。我在这里遗漏了什么,还是真的希望您在 with open() 之前使用 isfile() 或类似的东西?

Reh*_*gar 14

使用try/except处理异常

 try:
     with open( "a.txt" ) as f :
         print(f.readlines())
 except Exception:
     print('not found')
     #continue if file not found
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是,这将捕获任何异常,而不仅仅是 File Not Found,并且会掩盖您可能不知道的任何程序错误。您可以改为捕获 `FileNotFoundError` 或 `IOError`,具体取决于您的 Python 版本。 (6认同)