1

I wanted to use a temporary directory to create files into it but it just would not work until I put the code directly inside the "main". I would like to know why.

This code does not want to work, telling me "no such file or directory":

def use_temp_directory():
    tmpdir = tempfile.TemporaryDirectory()
    os.chdir(tmpdir.name)
    return tmpdir.name

if __name__ == "__main__":
    _ = use_temp_directory()
    create_file(filepath="./somefile.txt", mode="w")

This code do work:

if __name__ == "__main__":
    tmpdir = tempfile.TemporaryDirectory()
    os.chdir(tmpdir.name)
    create_file(filepath="./somefile.txt", mode="w")

For me both codes are the same, what I am missing?

1
  • 4
    I guess the temporary directory is only there till the calling process/scope ends. So your function finishes and the directory is destroyed Commented Apr 30, 2020 at 15:39

2 Answers 2

5

You only return the name of the directory, however the directory itself, tmpdir, runs out of scope when the function returns and is hence removed.

You can use TemporaryDirectory as a context manager which will remove the directory upon exit:

with tempfile.TemporaryDirectory() as td:
    # do something with `td` which is the name of the directory
Sign up to request clarification or add additional context in comments.

2 Comments

I know we can do that but I had reasons not to use this
"... which is the name of the directory" This part may be obvious, but for some reason I thought that td would be some OS-level identifier of the directory - I tried to find methods on the thing but there were none.
3

as just-learned-it commented, from documentation:

tempfile.TemporaryDirectory(suffix=None, prefix=None, dir=None)

This function securely creates a temporary directory using the same rules as mkdtemp(). The resulting object can be used as a context manager (see Examples). On completion of the context or destruction of the temporary directory object the newly created temporary directory and all its contents are removed from the filesystem.

1 Comment

Oh that is what I missed! The temporary directory object... thanks and thanks to just-learned-it, too

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.