tags:

views:

346

answers:

5
import sys
try:
     file = open("words.txt")
expect(IOError):

if file:
    print "%s" % file
else:
    print "Cant the %s file" % "words.txt"

this gives me an a error -

File "main.py", line 4 
    expect(IOError):
    SyntaxError: invaild syntax

What im going wrong/ how do you fix this

+11  A: 

Actually, it is except as in exception:

For instance:

except IOError:
    print "Error opening file!"
rogeriopvl
+1  A: 

It's except. Read this.

unbeknown
+1  A: 

I think you're looking for except. The error handling part of the python tutorial explains it well.

-John

John T
+4  A: 

I assume you are trying to handle exceptions. In that case, use except, not expect. In any case except is not a function, rather it precedes a block of error handling code. When using files, you may want to look at the with statement and try-except-finally. The correction to your code is-

import sys
try:
        file = open("words.txt")
except IOError:
      #Handle error
      pass
if file:
    print "%s" % file
else:
    print "Cant the %s file" % "words.txt"

I hope this helps.

batbrat
+1  A: 

>>> try:
...     f = open('words.txt')
... except IOError:
...     print "Cant the %s file" % "words.txt"
... else:
...     print "%s" % f

Mykola Kharechko