Python 2.5.2 - what was in place of the 'with' statement

I wrote my code for python 2.7, but the server has 2.5. How to rewrite the following code so that it runs 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 the reserved keyword in Python 2.6 Traceback (last last call): File "Main.py", line 7, from Extractor import Extractor File "/data/client/scripts/Extractor.py", line 29 with open (self._logFile, 'w') as from: ^ Syntax Error: invalid syntax

Thanks, Ron.

+6
source share
3 answers

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

 from __future__ import with_statement 
+19
source

If you cannot or do not want to use with , 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 thrown, regardless of whether an exception is thrown or not.

+3
source

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

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

The context manager with open() ... is pretty much the same here. Python automatically closes files when their objects are garbage collected (see question 575278 ), so out will be closed when the function by which it stops executing for some reason. In addition, the OS will close the file when the Python process terminates, if for some reason it terminates catastrophically before out.close() is executed.

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

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

See the β€œcontext manager” link above for an explanation. So how does it work? It opens a file, executes a block of code, then explicitly closes the file. How does the "old" version that I am describing work? It opens the file, executes your code block, then implicitly closes the file when its scope is completed or when the Python process terminates.

Save, but for the "explicit" vs "implicit" parts the functionality is identical.

-1
source

Source: https://habr.com/ru/post/900215/


All Articles