views:

273

answers:

2

Hello all,

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!

+5  A: 

Add this line before all other imports:

from __future__ import with_statement

The with statement is new in Python 2.6

Adam Bernier
I added the code but it did not make any difference, is there an alternative way to write the same code without the with statement?
mrlanrat
Had to step away. Glad Dan was able to help you out.
Adam Bernier
+3  A: 

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()
Daniel Stutzbach
This worked, thanks!However now I am getting a problem with the open function, the file does not exist. I want it to create the file if it does not exist. How should I do that? (I was under the impression that the open function could create the file too)
mrlanrat
@mrlanrat: show your code and the error message that led you to believe that the problem is a non-existent file
John Machin
Well, the file does not exist (I know that), and the error i get is:`fileh = open(file,'w')IOError: [Errno 2] No such file or directory: '~./appCounter'`
mrlanrat
@mrlanrat, Python by default will create nonexistant files. The problem is the directory. `~./appCounter` is not a valid directory. Python doesn't autoexpand `~` like the shell does and you have a misplaced `.`. You probably want to use the path `os.path.join(os.path.expanduser("~"), "appCounter")` or something like that.
Mike Graham
Note that `with` was introduced in 2.5 requiring `from __future__ import with_statement` and by default in 2.6. In 2.4 and previous, `try`/`finally` is required to ensure a file gets closed.
Mike Graham
It was a typo, I meant '~/.appCounter'So, what is the correct way to create a file in python if it does not yet exist?
mrlanrat
@mrlanrat, `open(filename, 'w')` does that. Did you read what I said about Python not automatically invoking the shell to expand ~?
Mike Graham
I added "file = os.path.join(os.path.expanduser('~'),file)" which made it work, thanks!
mrlanrat