Sometimes in someone's code (completely small programs, for example, solutions of Olympiad problems), you can see how I / O flows close at the very end. For example, in Java :

Scanner in = new Scanner(System.in); ... in.close(); 

Or in Python :

 in = open("input.txt", "r") ... in.close() 

How important is this point? It seems to me that he is not needed at all, because at the end of the program, and so all threads will close.

    1 answer 1

    You are right that when the program ends, the threads will be closed by the operating system. However, there are rules of "good tone" in programming that require closing a resource as soon as the need for it has disappeared.

    Here is a practical example of why this is “good style.” You write a certain program and do not close the resources, relying on the OS. But then your code from an independent unit turns into a part of the code of another, more powerful program. But your code does not release resources and as a result these resources are "hung" unclaimed. Moreover, your code is executed many times and each time it opens a resource and does not close it. This behavior at least leads to a waste of these resources, and in a more global perspective, slows down the work of not only the program, but also the computer on which it runs.

    I think that resources should always be closed. This is a good tone. But if you are lazy and all the program code fits on one screen, then you can do without it.


    By the way, there are constructions in the languages ​​indicated in the question that automatically close the resources. Here is what the code in question will look like.

    Java :

     try (final Scanner in = new Scanner(System.in)) { // ... } 

    Python :

     with open("input.txt", "r") as in: // ... 
    • one
      We should also mention the fact that the flow can close something nontrivial at closing, which the OS cannot do for it. If, with the further development of the program, a simple I / O stream is replaced by something more subtle, there will be a surprise upon exit. - Pavel Mayorov