英文:
Cannot delete folder created through python os.mkdir
问题
我有一个关于通过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'
英文:
I have an issue with folders created through a Python script that cannot be removed.
I have a python script that runs other scripts using the 'runpy' module. The scripts will then create a folder using os.mkdir and a lot of matplotlib figures will be saved in there. When the script has run, and I try to delete the folder, I'm not allowed.
Through os.listdir the folder will show up:
In[5]: import os
'aux' in os.listdir(r'C:\Python\Repositories\model-enveloper\Test')
Out[5]: True
But trying to delete the folder with os.rmdir (not possible through windows explorer either):
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>)
来删除带内容的目录。 -
尝试使用
C:/Python/Repositories/model-enveloper/Test/aux
而不是C:\Python\Repositories\model-enveloper\Test\aux
,@Bakuriu 已经提到了这一点。
因此,您可以尝试像这样删除它。
请注意,代码中的 HTML 编码已被移除。
英文:
This error occurred because of these reasons.
- You need to give admin permission to delete that directory.
rmdir
use for to delete Empty directories. make sure your mentioned directory is empty. If it is true useshutil.rmtree(<directory>)
to remove directry with contents.
import shutil
shutil.rmtree("<directory>")
- Try
C:/Python/Repositories/model-enveloper/Test/aux
instead ofC:\Python\Repositories\model-enveloper\Test\aux
@Bakuriu has mentioned it.
There for you can try to delete it like this
import os
os.rmdir(os.path.join("C:/Python/Repositories/model-enveloper/Test", "aux"))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论