Reputation: 607
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?
Upvotes: 12
Views: 7687
Reputation: 24942
The documentation at https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryDirectory says:
The directory name can be retrieved from the name attribute of the returned object. When the returned object is used as a context manager, the name will be assigned to the target of the as clause in the with statement, if there is one.
So, either you do without the context manager, and use t_dir.name
t_dir = tempfile.TemporaryDirectory()
os.path.join (t_dir.name, 'sample.png')
or, using a context manager, you can do:
with tempfile.TemporaryDirectory() as t_dir:
os.path.join (t_dir, 'sample.png')
Upvotes: 2
Reputation: 483
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)
Upvotes: 13