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



我有一个问题,通过 Python 脚本创建的文件夹无法删除。

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

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

In[5]: import os
'aux' in os.listdir(r'C:PythonRepositoriesmodel-enveloperTest')
Out[5]: True

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

In[6]: os.rmdir(r'C:PythonRepositoriesmodel-enveloperTestaux')
Traceback (most recent call last):
File "C:ProgramDataAnaconda3libsite-packagesIPythoncoreinteractiveshell.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:PythonRepositoriesmodel-enveloperTestaux')
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>")
  1. 尝试C:/Python/Repositories/model-enveloper/Test/aux而不是C:PythonRepositoriesmodel-enveloperTestaux@Bakuriu提到它。

在那里你可以尝试像这样删除它

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

最新更新