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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With