3

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?

gr0k
  • 789
  • 2
  • 9
  • 22

2 Answers2

1

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.

Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
0

The reason for this is that indata does not refer to a file object.

It refers to the data that the method read() returns, so when you try to call close() on that data, it will not work.

You need to keep separate references to open() and read() or look into using the with() builtin.

MrAlexBailey
  • 5,219
  • 19
  • 30