Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicitly closing files in python [duplicate]

Tags:

python

Looking at Learning Python the Hard Way. Example 17 opens a file, copies it, and then closes it. One of the study drills is to simplify the program down as much as possible. However when I simplified it, there doesn't seem to be any file to close. What I'm trying to understand with the one liner is what, if anything, needs to be closed.

For example-

in_file = open(from_file)
indata = in_file.read()
...
in_file.close()

This can be simplified to

indata = open(from_file).read()

I understand it's good practice to close the file after opening it, but both indata and from_file are strings. From some more digging, I understand this is unpythonic and should be done in 2 lines for readability, which would result in a file descriptor. However there is no open file descriptor here to close. Did I miss something? Should I have a file descriptor to explicitly close?

like image 313
gr0k Avatar asked Feb 23 '26 14:02

gr0k


1 Answers

Instead of doing this

indata = open(from_file).read()

You should have tried using the with keyword

with open(from_file) as f: indata = f.read()

In the former, you still have the file descriptor with you, even though you do not have any references left for it and there is no guarantee when the file will be closed. In the second approach, the file will be closed as soon as you are done with the statement execution.

like image 59
Anshul Goyal Avatar answered Feb 25 '26 04:02

Anshul Goyal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!