【问题标题】:Exception has occurred: TypeError rmdir: path should be string, bytes or os.PathLike, not TemporaryDirectory发生异常:TypeError rmdir: path should be string, bytes or os.PathLike, not TemporaryDirectory
【发布时间】:2021-02-19 08:40:07
【问题描述】:

请告诉我这段代码有什么问题?

代码:

import tempfile
import os
temp_dir=tempfile.TemporaryDirectory()
print("Directory name:", temp_dir)
os.removedirs(temp_dir)

错误:

Exception has occurred: TypeError
rmdir: path should be string, bytes or os.PathLike, not TemporaryDirectory

【问题讨论】:

    标签: python python-3.x python-3.9


    【解决方案1】:

    TemporaryDirectory 是一个对象,最初设计用于上下文(with 语句)以避免手动删除。它有一个cleanup 方法可以手动调用来删除临时文件夹,还有一个属性name 可以返回目录的完整路径。所以你可以直接打电话给temp_dir.cleanup(),或者os.removedirs(temp_dir.name)

    如果你真的想自己管理文件夹的生命周期,你应该使用tempfile.mkdtemp

    如需更多信息,Here 另一个关于同一主题的帖子。最后,请记住,TemporaryDirectory 旨在通过在幕后为您自动删除临时文件夹,让您的生活更轻松、更安全:

    with tempfile.TemporaryDirectory() as temp_dir_fullpath:
         # Beware temp_dir_fullpath != tempfile.TemporaryDirectory() !!!
         print('created temporary directory:', temp_dir_fullpath)
    

    对于短期目录非常方便,仅限于单个上下文(即不将路径传递给其他方法或类...)。但是,如果您需要自己管理它(主要是稍后在不同的上下文中重用它或将其传递给其他方法),我认为您最好自己完成这项工作,只使用简单的 tempfile.mkdtemp 方法,即tempfile.TemporaryDirectory 可能在幕后做的事情,为自动删除添加了额外的糖,代价是返回一个对象而不是一个普通的字符串。这样很明显,您是在自己处理删除而不是错误。

    【讨论】:

    • 如果你能向我解释更多关于这个或者在这种情况下,向我介绍该网站的一些案例
    【解决方案2】:

    解决milemabar 提到的问题的最简单方法之一是使用此 API:

    temp_dir.name
    

    【讨论】:

      猜你喜欢
      • 2020-10-08
      • 2018-12-23
      • 2021-09-12
      • 2020-11-07
      • 2021-06-25
      • 1970-01-01
      • 2018-06-07
      • 2015-08-25
      相关资源
      最近更新 更多