当我试图删除一个非空文件夹时,我得到一个“访问被拒绝”错误。我在尝试中使用了以下命令:os.remove("/folder_name")。
删除一个非空文件夹/目录最有效的方法是什么?
当我试图删除一个非空文件夹时,我得到一个“访问被拒绝”错误。我在尝试中使用了以下命令:os.remove("/folder_name")。
删除一个非空文件夹/目录最有效的方法是什么?
当前回答
从docs.python.org:
这个例子展示了如何在Windows中删除目录树 有些文件设置了只读位。它使用onerror 回调以清除只读位并重新尝试删除。任何 随后的失败将会传播。 导入os, stat 进口shutil Def remove_readonly(func, path, _) "清除只读位并重新尝试删除" 操作系统。chmod(路径,stat.S_IWRITE) func(路径) shutil。rmtree(目录,onerror = remove_readonly)
其他回答
import shutil
shutil.rmtree(dest, ignore_errors=True)
import shutil
shutil.rmtree('/folder_name')
标准库参考:shutil.rmtree。
根据设计,rmtree在包含只读文件的文件夹树上失败。如果您希望删除文件夹而不管它是否包含只读文件,请使用
shutil.rmtree('/folder_name', ignore_errors=True)
来自os.walk()的python文档:
# Delete everything reachable from the directory named in 'top',
# assuming there are no symbolic links.
# CAUTION: This is dangerous! For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files in os.walk(top, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
在python 3.4中,你可以使用:
import pathlib
def delete_folder(pth) :
for sub in pth.iterdir() :
if sub.is_dir() :
delete_folder(sub)
else :
sub.unlink()
pth.rmdir() # if you just want to delete the dir content but not the dir itself, remove this line
其中PTH是一个pathlib。路径实例。不错,但可能不是最快的。
我想添加一个“纯pathlib”方法:
from pathlib import Path
from typing import Union
def del_dir(target: Union[Path, str], only_if_empty: bool = False):
"""
Delete a given directory and its subdirectories.
:param target: The directory to delete
:param only_if_empty: Raise RuntimeError if any file is found in the tree
"""
target = Path(target).expanduser()
assert target.is_dir()
for p in sorted(target.glob('**/*'), reverse=True):
if not p.exists():
continue
p.chmod(0o666)
if p.is_dir():
p.rmdir()
else:
if only_if_empty:
raise RuntimeError(f'{p.parent} is not empty!')
p.unlink()
target.rmdir()
这依赖于Path是可排序的,长路径总是排在短路径之后,就像str一样。因此,目录将排在文件之前。如果我们反转排序,那么文件就会出现在它们各自的容器之前,所以我们可以简单地一次将它们逐个解除/rmdir链接。
好处:
它不依赖于外部二进制文件:所有东西都使用Python的电池包含的模块(Python >= 3.6) 这意味着它不需要重复启动一个新的子进程来解除链接 它非常快速和简单;你不必实现你自己的递归 它是跨平台的(至少,这是pathlib在Python 3.6中所承诺的;上述操作不能在Windows上运行) 如果需要,可以进行非常细粒度的日志记录,例如,记录每一次删除。