2

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.

Travis Cook
  • 161
  • 9

1 Answers1

6

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

3Doubloons
  • 2,088
  • 14
  • 26