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?

ava_punksmash
  • 357
  • 1
  • 4
  • 13
  • 4
    I guess the temporary directory is only there till the calling process/scope ends. So your function finishes and the directory is destroyed – Banana Apr 30 '20 at 15:39

2 Answers2

4

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
a_guest
  • 34,165
  • 12
  • 64
  • 118
  • I know we can do that but I had reasons not to use this – ava_punksmash Apr 30 '20 at 16:04
  • "... 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. – julaine Jun 19 '23 at 11:54
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.

sleepyhead
  • 419
  • 1
  • 5
  • 19