0

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?

0

2 Answers 2

2

Have a look at the tempfile module . Using the tempfile.TemporaryFile function seems to fit your need.

Sign up to request clarification or add additional context in comments.

1 Comment

This may solve my issue right now. Thanks for that. However, there may be other type of resources for which such modules will not be available
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.