Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With-As statement versus "=" Assignment? [duplicate]

What is the difference of using:

iFile = open("filename.txt",'r')

versus

with open("filename.txt",'r') as iFile:

Is one more efficient or allow more have more methods to access? It appears to me that the with-as statement is temporary and unreferences after the following block ends.

like image 957
Travis Cook Avatar asked Dec 14 '25 05:12

Travis Cook


1 Answers

Your first example simply opens the file and assigns the file object to a variable. You will need to manage closing the file yourself (ideally, in a try-finally block so you don't leak the file)

The second snippet uses a context manager to automatically close the file as you exit the with block, including by returning or raising an exception

like image 181
3Doubloons Avatar answered Dec 15 '25 19:12

3Doubloons