3

When properly using a file object you should either be closing it explicitly with

f = open("file.txt")
f.use()
f.close()

Or using the with method that makes sure the file is closed no matter what

with open("file.txt") as f:
    f.use()

But sometimes I want to grab a file only briefly. Maybe I just want to pull the string out of it and then discard the file. I sometimes write that like this:

fileStr = open("file.txt").read()

But this neither explicitly closes the file, nor does it use the with keyword. Does the file stay opened without any reference tied to it or does Python jettison the file intelligently? And if it doesn't, is there any way I could properly close it? I can't close after reading, as the close would be attempted on a string object:

fileStr = open("file.txt").read().close()

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    open("file.txt").read().close()
AttributeError: 'str' object has no attribute 'close'
SuperBiasedMan
  • 9,814
  • 10
  • 45
  • 73

0 Answers0