为什么这是Python中的意外缩进?

时间:2015-07-09 13:08:14

标签: python python-2.7

#!/usr/bin/python

try:
    f = open("/home/masi/r.raw", "r+")
    aBuf = f.seek(4) 
except:
    print "Error at position : ", position

events = []
for i in range(100):
    aBuf = f.seek(4);

    try:
        if aBuf[:4] == b'\xFA\xFA\xFA\xFA':
            print("E")

    except:
    #   print "\0"

f.close()

当我注释掉除了打印时,我收到了错误

    f.close()
    ^
IndentationError: expected an indented block

我想我需要尝试 - 除非因为if子句经常是假的。

为什么我会得到这种意外的压力?

2 个答案:

答案 0 :(得分:10)

except期待一个或多个陈述。

你可以写:

try:
    if aBuf[:4] == b'\xFA\xFA\xFA\xFA':
        print("E")
except:
    pass

警告
如评论中所述,使用except: pass不是一个好习惯  请参阅Why is “except: pass” a bad programming practice?

答案 1 :(得分:0)

来自events = []和down的代码需要在第一个try..except块中。 f.close()超出了范围。