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 Answers 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.
2 Comments
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 finallyYour 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.
exceptneeds to be at the same indentation level astry, and afterexceptyou need an indented block. And what is the linef.close()supposed to close? There is nof.exceptneeds to come beforefinally. Also,myfile = open('stats.txt', 'r')should be inside thetryas well, because it will generate an IOError if the file does not exist or cannot be opened.