Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading from a temporary directory in python: TypeError: expected str, bytes or os.PathLike object, not TemporaryDirectory

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?

like image 527
DonnRK Avatar asked Aug 04 '18 13:08

DonnRK


1 Answers

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 .name should be mentioned in the TemporaryDirectory docs, I discovered this by running dir(t_dir). (Edit: it's mentioned now)

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)
like image 179
gkw Avatar answered Sep 28 '22 20:09

gkw