如何删除目录?os.removedirs 和 os.rmdir 仅用于删除空目录吗? [英] How to remove a directory? Is os.removedirs and os.rmdir only used to delete empty directories?

查看:41
本文介绍了如何删除目录?os.removedirs 和 os.rmdir 仅用于删除空目录吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

导入操作系统os.chdir('/Users/mustafa/Desktop')os.makedirs('新文件/子文件')os.removedirs('新文件')

<块引用>

"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py",第 170 行,在 removeirsrmdir(名称)OSError: [Errno 66] 目录不为空:'new-file'

但是我认为我看到人们使用这些命令删除非空目录,那我做错了什么?谢谢

解决方案

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

导入shutilShutil.rmtree('/path/to/your/dir/')

回答您的问题:

<块引用>

os.removedirsos.rmdir 仅用于删除空目录吗?

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

<小时>

下面是来自官方 Python 文档的描述,它清楚地统计了这一点.

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

<块引用>

移除(删除)目录路径.仅在目录为空时有效,否则引发 OSError.为了删除整个目录树,可以使用shutil.rmtree().

os.removedirs(name)

<块引用>

递归删除目录.像 rmdir() 一样工作,不同之处在于,如果叶目录被成功删除,removedirs() 会尝试连续删除路径中提到的每个父目录,直到引发错误(该错误被忽略,因为它通常意味着父目录不为空).例如 os.removedirs('foo/bar/baz') 会先删除目录 'foo/bar/baz',然后删除 'foo/bar' 和 'foo' 如果它们是空的.如果无法成功删除叶目录,则引发 OSError.

Whenever I try to use them to remove dirs with things in them I get this error message

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'

However I think I saw people using those commands to delete dirs that weren't empty, so what am I doing wrong? Thanks

解决方案

You should be using shutil.rmtree to recursively delete directory:

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

Answer to your question:

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

Yes, they can only be used to delete empty directories.


Below is the description from official Python document which clearly stats that.

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.

这篇关于如何删除目录?os.removedirs 和 os.rmdir 仅用于删除空目录吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆