Closing a file


In my most recent exercise, I forgot to close the file. I hurriedly fixed this mistake, but had ran the code before I fixed it. Nothing visibly went wrong, and the output to the console was the exact same. What exactly can go wrong if files aren't properly closed?


Any writing to a file will only take place after the file is closed. If you end a session without closing, the update does not take place.


Thanks! But if you only want to read the file, does it make a difference? Is the only reason you would close it then for habit?


When you write to a file, you must close it to save any and all changes.

In addition to this, if you leave files open after ending use of it, it takes up unnecessary memory and makes your program use more resources than you typically want it to be using.

For example, if you wanted to make a resource-draining program, you could write a program that just makes, opens, and writes gibberish into different files forever. (Don't try it. :stuck_out_tongue: )


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.