This question already has an answer here:
I know there are plenty of articles and questions answered regarding reading files in python. But still I'm wondering what made python to have multiple ways to do the same task. Simply what I want to know is, what is the performance impact of using these two methods?
Using
with
statement is not for performance gain, I do not think there are any performance gains or loss associated with usingwith
statement, as long as, you perform the same cleanup activity that usingwith
statement would perform automatically.When you use
with
statement withopen
function, you do not need to close the file at the end, becausewith
would automatically close it for you.Also,
with
statement is not just for openning files, with is used in conjuction with context managers. Basically, if you have an object that you want to make sure it is cleaned once you are done with it or some kind of errors occur, you can define it as a context manager andwith
statement will call its__enter__()
and__exit__()
methods on entry to and exit from the with block. According to PEP 0343 -Also, performance testing of using
with
and not using it -