在python中捕获IOError

tek*_*agi 12 python exception-handling exception try-catch ioerror

我写了一个方法来做一些东西并捕获坏的文件名.应该发生的是如果路径不存在,它会抛出一个IOError.但是,它认为我的异常处理是错误的语法......为什么?

def whatever():
    try:
        # do stuff
        # and more stuff
    except IOError:
        # do this
        pass
whatever()

但在它进入调用之前whatever(),它会打印以下内容:

Traceback (most recent call last):
  File "", line 1, in 
  File "getquizzed.py", line 55
    except IOError:
         ^
SyntaxError: invalid syntax

进口时......帮忙?!

Bri*_*unt 10

检查你的缩进.这个无益的SyntaxError错误让我以前愚弄过.:)

从删除的问题:

I'd expect this to be a duplicate, but I couldn't find it.

Here's Python code, expected outcome of which should be obvious:

x = {1: False, 2: True} # no 3

for v in [1,2,3]:
  try:
      print x[v]
  except Exception, e:
      print e
      continue
I get the following exception: SyntaxError: 'continue' not properly in loop.

I'd like to know how to avoid this error, which doesn't seem to be 
explained by the continue documentation.

I'm using Python 2.5.4 and 2.6.1 on Mac OS X, in Django.

Thank you for reading
Run Code Online (Sandbox Code Playgroud)


Der*_*ley 6

如果您有权拥有较旧的安装,还有 1 个可能

您正在使用“as”语法:

     except IOError as ioe:

解析器被“as”绊倒了。

Usingas是 Python 2.6 及更高版本中的首选语法。

这是 Python 2.5 及更早版本中的语法错误。对于 2.6 之前的版本,请使用:

     except IOError, ioe: