Question: I’m quite new to Python programming. I was trying to learn try, except statements in Python with a simple example – may be to open a new file and write few contents into it. While handling the exception using except, I get a Syntax error at the line ‘except IOError, e‘.
I’m using Python version 3.5.1 and below is the example program:
#!/usr/bin/python try: fh = open("testfile", "r") fh.write("This is my test file for exception handling!!") except IOError, e: print ("Error: can\'t find file or read data",e) else: print ("Written content in the file successfully") fh.close()
When I execute the above program, I get the error message as shown below:
$ python file.py File "file.py", line 6 except IOError,e: ^ SyntaxError: invalid syntax
And the Python version is:
$ python --version Python 3.5.1
What could be the problem?
Using comma is not allowed from Python versions 3.x. Since you have Python version 3.5.1, you should use ‘as‘ instead of comma. It means, your program should be modified as below:
#!/usr/bin/python try: fh = open("testfile", "w") fh.write("This is my test file for exception handling!!") except IOError as e: print ("Error: can\'t find file or read data",e) else: print ("Written content in the file successfully") fh.close()
Difference between comma (,) and ‘as’ in Python except:
To summarize, the older version of Python (say earlier to 3.0), we use (,) as shown below
except Exception, e:
From Python version 3.0, the comma is replaced with ‘as’:
except Exception as e:
But wait, the comma is still valid if you are trying to catch more than one exception as shown below:
except (Exception1, Exception2) as e:
Getting SyntaxError: Missing parentheses in call to ‘print’? Check this tutorial.
That’s it. Hope it helps.