DEV Community

Cover image for Another way of working with temporary files
Jorge Alvarado
Jorge Alvarado

Posted on

8 4

Another way of working with temporary files

đź—‚ tmp-folder allows you to easily use a temporary folder during the execution of a function. After it is done executing, the folder will be automatically deleted (with all its content of course).

Install it

pip install tmp-folder
Enter fullscreen mode Exit fullscreen mode

Watch it in action

All you need to do is to decorate the function that needs a temporary folder and your function will get a free extra parameter, that's your tmp-folder:

# main.py
from pathlib import Path

from tmp_folder import use_tmp_folder


@use_tmp_folder  # This is the decorator
def do_some_stuff(my_tmp_folder: Path) -> Path:
    with open(my_tmp_folder / "some_file.txt", "w") as file:
        file.write("Hello World")

    assert my_tmp_folder.exists()

    return my_tmp_folder


if __name__ == "__main__":
    my_tmp_folder = do_some_stuff()
    assert not my_tmp_folder.exists()
    print("Everything went ok")

Enter fullscreen mode Exit fullscreen mode

We execute the code with python main.py:

Everything went ok
Enter fullscreen mode Exit fullscreen mode

✅ Cool, there are no assertion errors 👏🎉🎉🎉.

Key points:

  • The function that needs temporary stuff, is decorated with use_tmp_folder.
  • You get a new parameter in your decorated function (it can be named however you want, in this case my_tmp_folder). See how when you are calling do_some_stuff, you are not passing any argument, but on its definition there is a parameter, well, that's because tmp-folder adds it for you.
  • This new parameter is the temporary folder that tmp-folder gives you. You can store whatever you want in there. After the decorated function is done executing: bye bye temporary folder đź‘‹.
  • The parameter is a Path object, so you get all the cool things pathlib offers.
  • The decorator is built on top of Python's TemporaryDirectory, so you know is a safe thing to use.

For more details see the package documentation.
Image author.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (2)

Collapse
 
miguelsmuller profile image
Miguel Müller •

I liked knowing this approach

Collapse
 
jalvaradosegura profile image
Jorge Alvarado •

Thanks I'm glad you liked it :)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay