What is the best way in Python to check if a ZipFile object is not already closed?
For the moment I am doing this in a class:
try:
self.zf.open(archive_name).close()
except RuntimeError:
self.zf = zipfile.ZipFile(self.path)
with self.zf.open(archive_name) as f:
# do stuff...
Is there a better way?
Internally, there is an open file pointer called
fpthat get’s cleared on close; you can test for that yourself too:See the
zipfilemodule source; theopenmethod raises theRuntimeErrorexception ifnot self.fpis True.Note that relying on such internal, undocumented implementations can be hairy; if future implementations change your code will break, perhaps in subtle ways. Make sure you have good test coverage for your project.
Alternatively, you could create a ZipFile subclass and override the
.closemethod to track the state, which would be less at risk of breaking due to internal changes:and
with thanks to aknuds1 for the suggestion.