pythontemp

Why is tempfile.gettempdir() giving me the wrong path?


I have code that is trying to create a directory in my temp folder.

My code is :

temp = os.path.join(tempfile.gettempdir(), "HDD")
print(temp)

And it prints:

C:\Users\JEFFSA~1\AppData\Local\Temp\HDD

The error I receive is this:

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\JEFFSA~1\\AppData\\Local\\Temp\\HDD\\Path.txt'

The code that the error points to is:

with open(temp + "\\Path.txt", "w") as fh:
    fh.write(path)

I checked and my temp folder is actually this:

C:\Users\JeffSandor\AppData\Local\Temp

Why would the tempfile.gettempdir() give me a different path than it actually is?


Solution

  • You're trying to put stuff in a subdirectory of your temp folder, but you never actually made that subdirectory. You need to make it first.

    tempfile.gettempdir() gave you a valid path. The JEFFSA~1 thing is an 8.3 filename, a weird backward compatibility thing that exists due to file and directory name length restrictions on old Windows and DOS versions.