0

When I use open() in python 2.4.3, i get the following error

File "/tmp/chgjdbcconfig.py", line 16 with open("text.new", "wt") as fout: ^ SyntaxError: invalid syntax

I checked the python version and this is my output

Python 2.4.3

I was looking for advice on what could be the alternative. I am trying to edit lines in an XML file on a linux server and I have no control over the upgrades of the python version.

Any advice would be great!

Hououin Kyouma
  • 399
  • 5
  • 18
  • what is the `t` flag ... ive never seen that .. ahh google tells me its `ascii only mode` but I though just opening it without the `b` flag was sufficient for ascii only mode – Joran Beasley Feb 24 '14 at 17:50
  • @JoranBeasley Beasley I followed as it was form the link [replace-string-within-file-contents](http://stackoverflow.com/questions/4128144/replace-string-within-file-contents). My aim was to keep it as simple as possible. I wanted to perform the change contents of a file routine and I was not aware of the `with` problem... – Hououin Kyouma Feb 25 '14 at 00:17

2 Answers2

9

open isn't missing in 2.4. What's missing is the with statement (added in Python 2.5 as PEP-0343)

To do the same code without with:

fout = open("text.new", "wt")
# code working with fout file
fout.close()

Note the fout.close() is implicit when using with, but you need to add it yourself without


with statements have the added benefit of closing the file even if an exception is raised, so a more precise analogue would actually be:

fout = open("text.new", "wt")
try:
    # code working with fout file
finally:
    fout.close()
mhlester
  • 22,781
  • 10
  • 52
  • 75
0

it's not open() it is choking on. It is the with syntax. Context managers did not exist in Python 2.4.

you must explicitly close the file also.

Corey Goldberg
  • 59,062
  • 28
  • 129
  • 143