Python invalid syntax with "with" statement

38,433

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()
Share:
38,433

Related videos on Youtube

lanrat
Author by

lanrat

Updated on May 03, 2020

Comments

  • lanrat
    lanrat almost 4 years

    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!

  • lanrat
    lanrat almost 14 years
    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)
  • John Machin
    John Machin almost 14 years
    @mrlanrat: show your code and the error message that led you to believe that the problem is a non-existent file
  • lanrat
    lanrat almost 14 years
    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'
  • Mike Graham
    Mike Graham almost 14 years
    @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
    Mike Graham almost 14 years
    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.
  • lanrat
    lanrat almost 14 years
    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?
  • Mike Graham
    Mike Graham almost 14 years
    @mrlanrat, open(filename, 'w') does that. Did you read what I said about Python not automatically invoking the shell to expand ~?
  • lanrat
    lanrat almost 14 years
    I added "file = os.path.join(os.path.expanduser('~'),file)" which made it work, thanks!

Related