Is it correct to use a python statement with an instruction in combination with a try-except block ?:
try: with open("file", "r") as f: line = f.readline() except IOError: <whatever>
If so, then, given the old way of doing things:
try: f = open("file", "r") line = f.readline() except IOError: <whatever> finally: f.close()
Is the main advantage of the "with" expression here, that we can get rid of three lines of code? It seems to me that this is not convincing for me for this use case (although I understand that the "c" operator has other uses).
EDIT: Is the functionality of these two blocks of code the same?
EDIT2: The first few answers talk mostly about the benefits of using βc,β but they seem to be the ultimate benefit here. We were all (or should have) explicitly called f.close () for years. I believe that one advantage is that sloppy encoders will benefit from the use of "c".
python try-catch with-statement finally except
Jeff O'Neill Sep 04 2018-10-11T00: 00Z
source share