1

I am reading some data from a .txt file in Python using the following:

fileData = open("file.txt", "rb").read()

I know that you should always close opened files, and I assume in this case the file remains open. Is there a way to close the file without assigning it to a variable?

I'd like to avoid:

openedFile = open("file.txt", "rb")
fileData = openedFile.read()
openedFile.close()

And also:

with open("file.txt", "rb") as openedFile:
    fileData = openedFile.read()

It might not be possible, in which case okay, but just making sure.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578

1 Answers1

5

No, it's not possible. The with statement version is the idiomatic way to write it.

Though I would shorten openedFile to file or even f. Rule of thumb: The smaller the scope of a variable the shorter its name can be. Save the long names for long-lived identifiers.

with open("file.txt", "rb") as file:
    data = file.read()
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Wouldn't `open("file.txt", "rb").read()` actually work (at least in C Python)? Since there are no leftover references to the file handle, the garbage collector should close the open file. – Daniel Walker Apr 01 '21 at 02:04
  • 1
    @DanielWalker The answer to that is that there is no guarantee that even short-lived garbage will be collected before the interpreter itself terminates. See [this Q&A](https://stackoverflow.com/questions/60131055/will-garbage-collector-delete-reference-after-read). – kaya3 Apr 01 '21 at 02:11