The Python File Type documentation gives file.closed as a
bool indicating the current state of the file object. This is a read-only attribute; the
close()method changes the value. It may not be available on all file-like objects.
Given that it’s not guaranteed to be available on all file-like objects, is there another (better?) method of checking whether I’ve already got the file open, before trying to re-open it?
All file objects returned by
openhave theclosedattribute.File-like objects are objects that implement the same interface as
file(for exampleStringIO.StringIO), and the doc you’ve quoted indicates that it is not necessary to have aclosedattribute in order to implement such an interface.The same docs have notes sprinkled all over about what methods should be implemented in which file-like objects. They also have this to say about attributes:
Since the docs for the close methods state that “any operation which requires that the file be open will raise a ValueError“, the best way to check if a file-like object is closed is to simply use the file as if it were open, and catch
ValueErrorin case it is not.Not all file-like objects are
seek-able, so doing a test read to check if the object is closed (as I suggested to begin with) is a bad idea. This is because then you need to store what you’ve read in case the file turns out to be open, and then somehow prepend it to the actual read, when it happens. It’s better to simply assume it is open and do whatever you want to do right away, and then deal with closed files in the except clause.As has been pointed out in the comments, one does not simply re-open a closed file-like object. In the
StringIOexample, closing actually deletes the buffer, so the file-like object no longer has the information required to “re-open” itself as it used to be before closing.