py4e icon indicating copy to clipboard operation
py4e copied to clipboard

Explicit Closing of Files

Open A-M-R opened this issue 8 years ago • 1 comments

First off, I want to thank you for making this content freely accessible. I came to this site through Python for Everyone, and it is very helpful to have a text for the courses.

I have been reading through this version of the text as well as the Python 2 version and I noticed that in word.py , then in Chapter 7 and other examples in the book, the files that are opened in the programs are not explicitly closed. The only place where I saw close mentioned was in order to save a write to a file.

In reading from other sources and from instruction in a Bioinformatics course that I took, it was suggested that as a best practice, you should always explicitly close any files opened by your program, whether or not they were written to, to avoid corruption or inadvertent change.

I am not sure how much of an issue this is, but I wanted to raise it in case it is something that might benefit other learners starting out to get into the habit of writing programs that clean up after themselves when they make file and data calls.

A-M-R avatar Jun 30 '16 23:06 A-M-R

Thanks for the comment! You're exactly right that explicitly closing the file is good practice. Alternately, you'll see a with open(file) as f block used, at the end of which the file is automatically closed.

@csev this one's your call. Adding .close() or using with would be more idiomatic but would probably require a few updates to the text.

eah13 avatar Feb 28 '17 13:02 eah13

So there are very few examples where files are opened for write. For programs short programs that open, then read, and then finish there is not much need to close the handle. The text actually talks about this in Chapter 5:

_When you are done writing, you have to close the file to make sure that the last bit of data is physically written to the disk so it will not be lost if the power goes off.

>>> fout.close()

We could close the files which we open for read as well, but we can be a little sloppy if we are only opening a few files since Python makes sure that all open files are closed when the program ends. When we are writing files, we want to explicitly close the files so as to leave nothing to chance._

csev avatar Jan 03 '24 04:01 csev