1

I am trying to make this script work but it's... giving me indentation errors

#!/usr/bin/env python
import io

myfile = open('stats.txt', 'r')
dan = myfile.readline()
print dan
print "Your name: " + dan.split('|')[0]
try:
    myfile.write('blah')
finally:
        myfile.close()
except IOError:

Help?

3
  • 2
    except needs to be at the same indentation level as try, and after except you need an indented block. And what is the line f.close() supposed to close? There is no f. Commented Jan 17, 2011 at 22:56
  • At the moment you don't have anything after your except IOError: . Try to add some statement there and run the script. Commented Jan 17, 2011 at 23:13
  • 1
    except needs to come before finally. Also, myfile = open('stats.txt', 'r') should be inside the try as well, because it will generate an IOError if the file does not exist or cannot be opened. Commented Jan 17, 2011 at 23:14

3 Answers 3

3

Try-except-finally statement has the following syntax:

try:
    statement 1
except:
    statement 2
finally:
    statement 3

You're doing it a little bit wrong :) Try to fix)

Also, as Herohtar said, swap your finally and except statements. Finally really should go after except.

Sign up to request clarification or add additional context in comments.

2 Comments

Statements 1, 2 and 3 could be at different levels of indent, though, right? Python just needs an indented block, the levels of indent don't need to be the same. Of course, it would look much better if they were aligned...
All lines in statement 1 must be at the same indentation level. Let's say l1. All lines in statement 2 must be at same indentation level. Let's say l2. But l1 may be unequal with l2.
2
try:
    myfile.write('blah')
finally:
        f.close()
        except IOError:
myfile.close()

Why is the except IOError at the same indent level as f.close? Reading the code, it seems to me that it should look like

try:
    myfile.write('blah')
except IOError:
        myfile.close()
finally:
        f.close()

Also, I think that you mean myfile.close instead of f.close.

2 Comments

except has to come before finally
@Herohtar. Yeah, you're right, messed that up! Edited to fix problem.
2

Your Finally is indented two tabs.

Also, make sure you're not combining spaces and tabs.

Looking more at the code:

Your except should be on the same level as the Try/Finally, and needs an indented block after.

Why f.close? There's no f.open.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.