Using close in Python

2

Why is it necessary to close ( close ) a file ( file ) open ( open ) in Python? What would happen if you left the file open?

    
asked by Edgar Galindez 17.02.2018 в 23:38
source

1 answer

4

Depending on the version of Python you are using, the file will be closed when it stops referencing, or will close later (when the garbage collector passes), or it may never close ... and that may result to some problems:

  • You can lose data : if the file has been opened in write mode, some of the changes may not be saved or made effective until the file is closed. So if you do not close the file, you could lose data if the program ends unexpectedly.
  • You may lose the ability to open files : the operating system limits the number of files that can be opened at the same time. If your program works with many files and you do not close them after opening them, they can accumulate open and reach the established limit, causing the program to end up failing.
  • The program can slow down : open files occupy space in memory and take up system resources, not closing them can end up affecting the performance and speed of your program.
  • Files can be blocked : for example in Windows, when a file is opened, locked and can not be operated with it until it is closed (the typical error of "the operation can not be performed because the file is in use ").
  • You lose control of the program : by not closing the open files, you depend on Python and the garbage collector closing them for you, and you do not know when or how that will happen. By closing them yourself you gain control over your program and make your programming more robust and portable.

I am not saying that all those problems are going to happen but, with the occurrence of some of them, their impact could be very negative in your application. That's why it's important (and it's considered good practice) to close the files once you've finished working with them.

    
answered by 18.02.2018 / 00:24
source