gpt4 book ai didi

python - 无法删除通过 python os.mkdir 创建的文件夹

转载 作者:行者123 更新时间:2023-12-01 06:37:16 31 4
gpt4 key购买 nike

我遇到通过 Python 脚本创建的文件夹无法删除的问题。

我有一个 python 脚本,它使用“runpy”模块运行其他脚本。然后,脚本将使用 os.mkdir 创建一个文件夹,并且许多 matplotlib 图形将保存在其中。当脚本运行时,我尝试删除该文件夹,但不允许。

通过 os.listdir 文件夹将显示:

In[5]: import os
'aux' in os.listdir(r'C:\Python\Repositories\model-enveloper\Test')
Out[5]: True

但尝试使用 os.rmdir 删除文件夹(也无法通过 Windows 资源管理器删除):

In[6]: os.rmdir(r'C:\Python\Repositories\model-enveloper\Test\aux')
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2963, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-6-c835caa088bf>", line 1, in <module>
os.rmdir(r'C:\Python\Repositories\model-enveloper\Test\aux')
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:\\Python\\Repositories\\model-enveloper\\Test\\aux'

最佳答案

由于这些原因发生此错误。

  1. 您需要授予管理员删除该目录的权限。
  2. rmdir用于删除空目录。确保您提到的目录是空的。如果是这样,请使用 shutil.rmtree(<directory>)删除包含内容的目录。
import shutil
shutil.rmtree("<directory>")
  • 尝试 C:/Python/Repositories/model-enveloper/Test/aux而不是C:\Python\Repositories\model-enveloper\Test\aux @Bakuriu 提到过。
  • 你可以尝试这样删除

    import os
    os.rmdir(os.path.join("C:/Python/Repositories/model-enveloper/Test", "aux"))

    关于python - 无法删除通过 python os.mkdir 创建的文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59610719/

    31 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com