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?