[Tutor] Mysterious syntax errors and file-reading issues
Alan Gauld
alan.gauld at freenet.co.uk
Fri Jul 14 23:13:54 CEST 2006
> def exists('/Users/username/Documents/python/word_bank.txt'):
> return os.access('/Users/usernameDocuments/python/word_bank.txt',
> 1. I get a "syntax error" message at the line that starts with "def
> exists", but I don't see the mistake.
You are defining a function with a constant as an agument.
You cannot do that you need a variable (technically a parameter)
The parameter can have a default value if you like so:
> def
> exists(filename='/Users/username/Documents/python/word_bank.txt'):
> return os.access(filename,
> os.F_OK)
> for line in
> open('/Users/username/Documents/python/word_bank.txt').readlines():
> 2. If I take out that line, I get "errno 2" at the next line; the
> interpreter seems convinced that that file doesn't exist, though it
> does.
defining a function is different from executing it. After the
definition
you still need to call it and check the result.
However usually its good enough just to use a try/except to catch
errors for missing files. In pseudo code like this:
try:
for line in open(filename):
process line
except: print ooops couldn't process file!
You only need to use exists() if you really need the detail of why
it failed - maybe with a view to taking corrective action before
trying
again...
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list