+ 1
What is the consequence if we don't put the close command in our program?
3 Antworten
+ 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.
+ 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.
0
apaños..?