17

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!

2
  • What version of Python are you using? Commented May 3, 2010 at 2:48
  • same problem on Python 3.6.8 on Oracle Linux 8 (supported til 2029) Commented Dec 12, 2023 at 4:55

1 Answer 1

26

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()
Sign up to request clarification or add additional context in comments.

8 Comments

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: show your code and the error message that led you to believe that the problem is a non-existent file
@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.
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.
@mrlanrat, open(filename, 'w') does that. Did you read what I said about Python not automatically invoking the shell to expand ~?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.