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
  • 327
  • 3
  • 12
  • 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

2

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
  • 30,279
  • 8
  • 49
  • 99
2

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
  • 379
  • 1
  • 4
  • 18