如何删除目录?os.removedirs和os.rmdir是否只用于删除空目录?

2024-10-05 10:02:21 发布

您现在位置:Python中文网/ 问答频道 /正文

每当我试图用它们来移除里面有东西的dir时,我就会收到这个错误消息

import os
os.chdir('/Users/mustafa/Desktop')
os.makedirs('new-file/sub-file')
os.removedirs('new-file') 

"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 170, in removedirs rmdir(name) OSError: [Errno 66] Directory not empty: 'new-file'

但是我想我看到有人使用这些命令来删除不是空的目录,所以我做错了什么?谢谢


Tags: import消息newos错误dirlibraryusers
1条回答
网友
1楼 · 发布于 2024-10-05 10:02:21

您应该使用^{}递归删除目录:

import shutil
shutil.rmtree('/path/to/your/dir/')

回答你的问题:

Is os.removedirs and os.rmdir only used to delete empty directories?

是的,它们只能用于删除空目录。


下面是来自Python官方文档的描述,它清楚地说明了这一点。

^{}

Remove (delete) the directory path. Only works when the directory is empty, otherwise, OSError is raised. In order to remove whole directory trees, shutil.rmtree() can be used.

^{}

Remove directories recursively. Works like rmdir() except that, if the leaf directory is successfully removed, removedirs() tries to successively remove every parent directory mentioned in path until an error is raised (which is ignored, because it generally means that a parent directory is not empty). For example, os.removedirs('foo/bar/baz') will first remove the directory 'foo/bar/baz', and then remove 'foo/bar' and 'foo' if they are empty. Raises OSError if the leaf directory could not be successfully removed.

相关问题 更多 >

    热门问题