Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2.5.2- what was instead of 'with' statement

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.

like image 982
Ron D. Avatar asked Oct 27 '11 15:10

Ron D.


2 Answers

In Python 2.5, you actually can use the with statement -- just import it from __future__:

from __future__ import with_statement
like image 105
Sven Marnach Avatar answered Oct 08 '22 15:10

Sven Marnach


If you can't, or don't want to use with, then use finally:

gzipHandler = gzip.open(gzipFile)
out = open(txtFile, 'w')
try:
    for line in gzipHandler:
        out.write(line)
finally:
    out.close()
    gzipHandler.close()

The cleanup code in the finally clause will always be excecuted, whether an exception is raised, or not.

like image 31
ekhumoro Avatar answered Oct 08 '22 16:10

ekhumoro