1
#!/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()

when I commented out the print of except, I get the error

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

I think I need to have try-except because the if-clause is false often.

Why do I get this unexpected indendation?

Léo Léopold Hertz 준영
  • 134,464
  • 179
  • 445
  • 697
  • 7
    Your `except` expects a valid indented block. It doesn't have one. That is why it fails. You can use `pass` here. But beware of the Jabberwocky and keep in mind [`except: pass` is a bad programming practise](http://stackoverflow.com/questions/21553327/why-is-except-pass-a-bad-programming-practice). – thefourtheye Jul 09 '15 at 13:09
  • 1
    because your except block has no instruction. You can use `pass` – daouzli Jul 09 '15 at 13:09
  • This code has problems beyond the fact that the 2nd except block doesn't have any actual code in it. [file.seek()](https://docs.python.org/2/library/stdtypes.html#file.seek) does not have a return value, so aBuf will always be [None](https://docs.python.org/2/c-api/none.html#the-none-object). – PTBNL Jul 09 '15 at 15:01
  • When you say "*I need to have try-except because the if-clause is false often*" do you think that if your `if` evaluates to `False` that the `except` block will be triggered? Because that is not the case. In that situation what you are looking for is `else`. – kylieCatt Jul 09 '15 at 17:37

2 Answers2

10

except is expecting one or more statements.

You could write:

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

Warning
As stated in the comments, it is not a good practice to use except: pass.
See Why is “except: pass” a bad programming practice?.

Community
  • 1
  • 1
Mel
  • 5,837
  • 10
  • 37
  • 42
0

Your code from events = [] and down needs to be inside of the first try..except block. The f.close() is out of scope.

Doug
  • 3,472
  • 3
  • 21
  • 18
  • It's not out of scope. That's not how scoping works in Python. And if that were the problem, he'd be getting a `NameError` instead of an `IndentationError`. – Cairnarvon Jul 09 '15 at 13:17