Python Forum

Full Version: Error on open of file created with tempfile.TemporaryDirectory()
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
The below code gives an error on the line: tfp = open(path, "w+t")
Anyone know why?

Error:
Exception has occurred: NotADirectoryError [WinError 267] The directory name is invalid: 'C:\\Users\\gener\\AppData\\Local\\Temp\\tmp99c64lys\\tempfile.txt' File "C:\Users\gener\OneDrive\My Documents\Python Programming\run.py", line 10, in <module> print(tfp.read())
import os
import tempfile

# create a temporary directory using the TemporaryDirectory class
with tempfile.TemporaryDirectory() as tdp:
    path = os.path.join(tdp, "tempfile.txt")
    tfp = open(path, "w+t")
    tfp.write("This is a temp file in temp dir")
    tfp.seek(0)
    print(tfp.read())
The exception traceback does not seem to agree with your claim that the code fails on the line tfp = open(...). Can you post the exact code and the full traceback?
You've set up a context for the temp directory, but not for the tfp file. So when the end of the code is reached, the tfp file isn't immediately closed.

On linux, an open file doesn't matter, you can still delete the file and the directory. But on Windows, the removal will fail.

Either explictly close() the tfp file, or open it in a with context so that it is closed before the end of the TemporaryDirectory context.
In other words, there is not a problem with line 10 other than it being the last line of the context created by this:
with tempfile.TemporaryDirectory() as tdp:
When your program finishes line 10 it exits the context defined for tdp and calls the exit function. The exit function deletes the directory, unsuccessfully.

Why aren't you using TemporaryFile() instead of TemporaryDirectory()?
Thank you all! Adding the tfp.close() resolved it as I am on Windows 10.

The code is from a video Python course I am taking. The code works for the instructor in the video, and he is on Linux, or a Linux like platform. The comment about it not mattering on Linux explains it.

In the same lesson he had demonstrated tempfile.TemporaryFile just before a demo of tempfile.TemporaryDirectory.