关于python:如何删除目录?os.removedirs和os.rmdir是否仅用于删除空目录?

How to remove a directory? Is os.removedirs and os.rmdir only used to delete empty directories?

本问题已经有最佳答案,请猛点这里访问。

每当我试图使用它们删除其中包含内容的目录时,都会收到此错误消息

1
2
3
4
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'

不过,我认为我看到有人使用这些命令删除非空的目录,那么我做错了什么?谢谢


您应该使用shutil.rmtree递归删除目录:

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

回答你的问题:

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

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

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

os.rmdir(path, *, dir_fd=None)

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.

os.removedirs(name)

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.