6

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.

Ron D.
  • 3,774
  • 6
  • 31
  • 39

3 Answers3

20

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

from __future__ import with_statement
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
3

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.

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
-1

The "old" version of the code inside your try/except block would be:

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

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), so out 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 before out.close() gets executed.

The with open() context manager will expand to approximately:

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

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.

Community
  • 1
  • 1
Kirk Strauser
  • 30,189
  • 5
  • 49
  • 65
  • 1
    This code is totally different from what a context manager does. This code simply eats all exceptions occuring during the whole operation, without giving any diagnostics (side note: you never want a bare `except` clause in production code!). A context manager ensures that the clean-up code is executed even if an exception occured, but lets the exception propagate. This is could be simulated by a try/finally statement. – Sven Marnach Oct 27 '11 at 16:27
  • It's totally different from what *a* context manager does in general. But can you give an example of how it's substantially different from what *this* context manager does in this particular case? What would be the difference in behavior? – Kirk Strauser Oct 27 '11 at 16:55
  • In this case, the difference is the same as in the general case. Your code does not ensure that the cleanup code is executed (i.e., your code doesn't ensure the file will be closed). – Sven Marnach Oct 27 '11 at 16:58
  • @SvenMarnach I expanded my answer to clarify it. Also, the `except` part you mention in your first comment was the OP's, not mine. I agree that a bare `except` is a bad idea and I (almost) never use them, but for purposes of demonstration I didn't want to change his code too much. – Kirk Strauser Oct 27 '11 at 18:27
  • OK, it's much clearer now. I've taken back my downvote, though some of the details are still wrong. One example of a wrong detail is "`out` will be closed when the function it's in stops executing for some reason." If the function executes due to an exception, the exception will contain a traceback with a link to the frame, preventing garbage collection of the file object. Moreover, in implementations of Python other than CPython, you can't even be sure that the file is garbage collected when the function returns. – Sven Marnach Oct 27 '11 at 18:43