Search code examples
pythonfilegarbage-collection

If i open a file, then set it to a variable, does it close the file?


In python, if i opened a file:

file = open('file.txt','r')
//  read the file and stuff
file = None // does this close the file and free up resources?

then set it to something else, would that file be closed? would there be any downsides to doing this?

I am aware that 'file.close()' does this, but i want to know if i can just set it to something else instead.


Solution

  • You should always close the file every time you open it unless you are using with open.