Shai106
Shai106

Reputation: 35

What does it mean for a "reference object of a file to be reassigned to another file"?

If I create a variable from a file example = open(example_file) and then read that file into a variable example_read = example.read() then I need to close the file later example.close().

But if I read directly into the variable example_read = open(example_file).read() then I don't need to close it (i.e. it's not open). (Via LPTHW)

Why is it already closed? I don't understand the following explanation - isn't the same thing being done whether it's done with an intermediate variable example or just directly to example_read?

"Python automatically closes a file when the reference object of a file is reassigned to another file." - TutorialsPoint

Upvotes: 1

Views: 243

Answers (2)

Sci Prog
Sci Prog

Reputation: 2691

It means, for example

f = open( 'file1.txt', 'r' )
f = open( 'file2.txt', 'r' )

On the second line, the reference f is reassigned to another file (i.e. file2.txt). So python will automatically close file1.txt.

N.B. your question is about re-opening the same file. The answer is the same. I used two different files on purpose to make the explanation clearer.

Upvotes: 0

chepner
chepner

Reputation: 531708

The file object created by the call to open is anonymous, in the sense that you don't create a reference to it. Once the call to read on that object completes and its return value is assigned to example_read, the object can be garbage collected, at which time the underlying file will be closed. However, you don't know exactly when that will happen, so the file could remain open for an unspecified period of time.

Better practice is to avoid such anonymous file objects and/or use a with statement to ensure that the file is closed when you are done with it.

with open(example_file) as fh:
    example_read = fh.read()

This guarantees that the file will be closed as soon as the with statement completes, even with an anonymous (although useless) object created by

with open(example_file):
    # Do something without the file object.

Upvotes: 2

Related Questions