I have created a temporary directory in python where I am saving a bunch of .png files for later use. My code seemingly works fine up until the point where I need to access those .png files - when I do so, I get the following error:
TypeError: expected str, bytes or os.PathLike object, not TemporaryDirectory
The error is thrown when I pass the temporary directory in os.path.join:
import os
import tempfile
t_dir = tempfile.TemporaryDirectory()
os.path.join (t_dir, 'sample.png')
Traceback (most recent call last):
File "<ipython-input-32-47ee4fce12c7>", line 1, in <module>
os.path.join (t_dir, 'sample.png')
File "C:\Users\donna\Anaconda3\lib\ntpath.py", line 75, in join
path = os.fspath(path)
TypeError: expected str, bytes or os.PathLike object, not TemporaryDirectory
However, using gettempdir() seems to work fine.
import os
import tempfile
t_dir = tempfile.gettempdir()
os.path.join (t_dir, 'sample.png')
The python docs suggests tempfile.TemporaryDirectory works using the same rules as tempfile.mkdtemp() (https://docs.python.org/3.6/library/tempfile.html#tempfile.TemporaryDirectory), and I would think tempfile.TemporaryDirectory is the preferred method for python 3.x. Any ideas why this throws an error or if one of these methods is preferred over the other for this use case?
I'm not sure why the error occurs, but one way to get around it is to call .name
on the TemporaryDirectory
:
>>> t_dir = tempfile.TemporaryDirectory()
>>> os.path.join(t_dir.name, 'sample.png')
'/tmp/tmp8y5p62qi/sample.png'
>>>
You can then run t_dir.cleanup()
to remove the TemporaryDirectory
later.
FWIW, I think (Edit: it's mentioned now).name
should be mentioned in the TemporaryDirectory docs, I discovered this by running dir(t_dir)
.
You should consider placing it in a with
statement, e.g. adapted from the one in the official docs linked above:
# create a temporary directory using the context manager
with tempfile.TemporaryDirectory() as t_dir:
print('created temporary directory', t_dir)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With