Python invalid syntax with "with" statement

lanrat picture lanrat · May 3, 2010 · Viewed 34.5k times · Source

I am working on writing a simple python application for linux (maemo). However I am getting SyntaxError: invalid syntax on line 23: with open(file,'w') as fileh:

The code can be seen here: http://pastebin.com/MPxfrsAp

I can not figure out what is wrong with my code, I am new to python and the "with" statement. So, what is causing this code to error, and how can I fix it? Is it something wrong with the "with" statement?

Thanks!

Answer

Daniel Stutzbach picture Daniel Stutzbach · May 3, 2010

Most likely, you are using an earlier version of Python that doesn't support the with statement. Here's how to do the same thing without using with:

fileh = open(file, 'w')
try:
    # Do things with fileh here
finally:
    fileh.close()