Reputation: 1015
I have a python class ReportGenerator which needs temporary directory to store intermediate files. Once object of ReportGenerator is destroyed my code is required to delete temporary folder.
Where to place directory removal code to make sure that once object is not referenced, the temp folder will be deleted.
In C++ it is obvious to delete folder in destructor of class. In python there is a __del__
but as I understand from other posts it is not recommended to use it in such situation. So in general what is a right way in python so one object can own a resource and release once it destroyed?
Upvotes: 0
Views: 689
Reputation: 46869
tempfile.TemporaryDirectory
in a with
context does what you want. this is from the examples for tempfile
:
# create a temporary directory using the context manager
>>> import tempfile
>>> with tempfile.TemporaryDirectory() as tmpdirname:
... print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
when you exit the with block, the directory and its contents are recursively removed.
Upvotes: 0
Reputation: 3790
Have a look at the tempfile module . Using the tempfile.TemporaryFile function seems to fit your need.
Upvotes: 2