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

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


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 managerwith tempfile.TemporaryDirectory() as t_dir:    print('created temporary directory', t_dir)


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')