I wrote my code for python 2.7 but the server has 2.5. How do i rewrite the next code so it will run in python 2.5.2:
gzipHandler = gzip.open(gzipFile)
try:
with open(txtFile, 'w') as out:
for line in gzipHandler:
out.write(line)
except:
pass
Right now, when i try to run my script I get this error:
Warning: 'with' will become a reserved keyword in Python 2.6 Traceback (most recent call last): File "Main.py", line 7, in from Extractor import Extractor File "/data/client/scripts/Extractor.py", line 29 with open(self._logFile, 'w') as out: ^ SyntaxError: invalid syntax
Thanks, Ron.
If you can't, or don't want to use
with
, then usefinally
:The cleanup code in the
finally
clause will always be excecuted, whether an exception is raised, or not.The "old" version of the code inside your try/except block would be:
The
with open() ...
context manager is effectively the same thing here. Python closes files automatically when their objects are garbage collected (see question 575278 for details), soout
will be closed when the function it's in stops executing for some reason. Furthermore, the OS will close the file when the Python process terminates should it fail catastrophically for some reason beforeout.close()
gets executed.The
with open()
context manager will expand to approximately:See the above link to "context manager" for an explanation. So how does it work? It opens the file, executes your block of code, then explicitly closes the file. How does the "old" version I describe work? It opens the file, executes your block of code, then implicitly closes the file when its scope is finished or when the Python process terminates.
Save but for the "explicit" vs "implicit" parts, the functionality is identical.
In Python 2.5, you actually can use the
with
statement -- just import it from__future__
: