What is the consequence if we don't put the close command in our program? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What is the consequence if we don't put the close command in our program?

17th May 2016, 6:51 AM
Ade Kurniawan
Ade Kurniawan - avatar
3 Answers
+ 8
There are several possible problems. On OS level, processes have a limited number of open files that they can maintain, so there could be a problem for long or complex scripts. Then there is a question of Python implementation that you use. There is no guarantee when will open files be closed once they are no longer referenced. It could be immediately or it could be much latter. And some python implementations don't even do it, but leave it up to OS to close the files when Python interpreter exits. And there is a problem that if the file is opened in write, or read-write mode, you don't know when the data is flushed if you don't close it explicitly.
17th May 2016, 7:22 AM
+ 1
I think NBab has given an excellent explanation. But I think there is one more advantage in using "with". Suppose you are working with a series of large files, where you are reading the content of each file to memory and do some computation. If you forget to close each file properly, you may quickly run out of memory or you may cause the OS to do unnecessary swaps, which affects the system performance.
4th Jul 2016, 10:48 PM
6th Jul 2016, 1:05 PM
Boris Andrés Litardo Moyano
Boris Andrés Litardo Moyano - avatar