Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python invalid syntax with "with" statement

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!

like image 708
lanrat Avatar asked May 03 '10 02:05

lanrat


People also ask

How do I fix invalid SyntaxError in Python?

You can clear up this invalid syntax in Python by switching out the semicolon for a colon. Here, once again, the error message is very helpful in telling you exactly what is wrong with the line.

Why is my else statement invalid syntax Python?

In Python code in a file, there can't be any other code between the if and the else . You'll see SyntaxError: invalid syntax if you try to write an else statement on its own, or put extra code between the if and the else in a Python file.

What happens if you execute a statement with invalid syntax?

When a SyntaxError like this one is encountered, the program will end abruptly because it is not able to logically determine what the next execution should be. The programmer must make changes to the syntax of their code and rerun the program.

What is SyntaxError in Python with example?

Syntax errors are mistakes in the use of the Python language, and are analogous to spelling or grammar mistakes in a language like English: for example, the sentence Would you some tea? does not make sense – it is missing a verb. Common Python syntax errors include: leaving out a keyword.


1 Answers

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()
like image 144
Daniel Stutzbach Avatar answered Sep 22 '22 12:09

Daniel Stutzbach