从 python 中的临时目录读取:TypeError: expected str, bytes or os.PathLike object, not TemporaryDirectory

Don*_*nRK 8 python windows filepath temporary-files

我在 python 中创建了一个临时目录,我在其中保存了一堆 .png 文件供以后使用。我的代码在我需要访问这些 .png 文件之前似乎工作正常 - 当我这样做时,我收到以下错误:

TypeError: expected str, bytes or os.PathLike object, not TemporaryDirectory
Run Code Online (Sandbox Code Playgroud)

当我在 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
Run Code Online (Sandbox Code Playgroud)

但是,使用 gettempdir() 似乎工作正常。

import os
import tempfile
t_dir = tempfile.gettempdir()
os.path.join (t_dir, 'sample.png')
Run Code Online (Sandbox Code Playgroud)

python 文档建议 tempfile.TemporaryDirectory 使用与 tempfile.mkdtemp() ( https://docs.python.org/3.6/library/tempfile.html#tempfile.TemporaryDirectory )相同的规则工作,我认为 tempfile.TemporaryDirectory 是python 3.x 的首选方法。任何想法为什么会引发错误,或者对于此用例,这些方法中的一种是否比另一种更受欢迎?

gkw*_*gkw 7

我不知道为什么会出现错误,但一个办法来解决它调用.nameTemporaryDirectory

>>> t_dir = tempfile.TemporaryDirectory()
>>> os.path.join(t_dir.name, 'sample.png')
'/tmp/tmp8y5p62qi/sample.png'
>>>
Run Code Online (Sandbox Code Playgroud)

然后您可以运行t_dir.cleanup()以删除TemporaryDirectory后者。

FWIW,我认为.name应该在TemporaryDirectory 文档中提到,我通过运行dir(t_dir). (编辑:现在提到了)

您应该考虑将其放在with声明中,例如改编自上面链接的官方文档中的声明:

# create a temporary directory using the context manager
with tempfile.TemporaryDirectory() as t_dir:
    print('created temporary directory', t_dir)
Run Code Online (Sandbox Code Playgroud)