Why should I close files in Python? [duplicate]

For the most part, not closing files is a bad idea, for the following reasons:

  1. It puts your program in the garbage collectors hands – though the file in theory will be auto closed, it may not be closed. Python 3 and Cpython generally do a pretty good job at garbage collecting, but not always, and other variants generally suck at it.

  2. It can slow down your program. Too many things open, and thus more used space in the RAM, will impact performance.

  3. For the most part, many changes to files in python do not go into effect until after the file is closed, so if your script edits, leaves open, and reads a file, it won’t see the edits.

  4. You could, theoretically, run in to limits of how many files you can have open.

  5. As @sai stated below, Windows treats open files as locked, so legit things like AV scanners or other python scripts can’t read the file.

  6. It is sloppy programming (then again, I’m not exactly the best at remembering to close files myself!)

Hope this helps!

Leave a Comment