0

What is the difference between:

data = open(filename).read()

And:

with open(filename) as handle:
    data = handle.read()

?

I would like to know:

  • Will the .close() method be called in both cases?
  • At roughly the same time? I have the impression in the first case the .close() method will only be called when garbage collection kicks in.

I like the first version because it's a single line.

volingas
  • 1,023
  • 9
  • 21
  • 1
    Garbage collection isn't required to close the file, but it does so in CPython. – Barmar May 11 '20 at 06:07
  • @Barmar: your comment is not clear. Is garbage collection required to free the descriptor or not? I am on CPython, but it does not matter: this is python code, and should run with any python version (3.x). When is the filedescriptor freed in the first version? – volingas May 11 '20 at 06:12
  • Read the linked question for details. – Barmar May 11 '20 at 06:16
  • @Barmar very different. The other question does not talk about temporary objects. In this question there is an object created which is not referenced by any variable, ever. Will be garbage collected immediately? – volingas May 11 '20 at 06:30
  • Garbage collection just cares about references, they don't have to be variables. It's implementation dependent whether it will be GCed immediately. – Barmar May 11 '20 at 06:59
  • @volingas then the answer is no, the file descriptor is *not* guaranteed to be free in your first version. It *happens* to be closed in the `__del__` method of file objects, but even that isn't really guaranteed to be called. The *recommended* way to work with resources like this is to use a context manager. That is why they are there. Try this simply script: `python -c "open('test.txt', 'w').write('hello')"` in your terminal. Now open `test.txt`. Notice that the file is empty? That's because the file handle didn't flush it's buffer, because `__del__` was not called. – juanpa.arrivillaga May 11 '20 at 06:59
  • @juanpa.arrivillaga the file is not empty in my system – volingas May 11 '20 at 08:25

0 Answers0