当我试图删除一个非空文件夹时,我得到一个“访问被拒绝”错误。我在尝试中使用了以下命令:os.remove("/folder_name")。
删除一个非空文件夹/目录最有效的方法是什么?
当我试图删除一个非空文件夹时,我得到一个“访问被拒绝”错误。我在尝试中使用了以下命令:os.remove("/folder_name")。
删除一个非空文件夹/目录最有效的方法是什么?
当前回答
在我的情况下,删除的唯一方法是使用所有的可能性,因为我的代码应该运行cmd.exe或powershell.exe。如果是你的情况,只需要用下面的代码创建一个函数就可以了:
#!/usr/bin/env python3
import shutil
from os import path, system
import sys
# Try to delete the folder ---------------------------------------------
if (path.isdir(folder)):
shutil.rmtree(folder, ignore_errors=True)
if (path.isdir(folder)):
try:
system("rd -r {0}".format(folder))
except Exception as e:
print("WARN: Failed to delete => {0}".format(e),file=sys.stderr)
if (path.isdir(self.backup_folder_wrk)):
try:
system("rd /s /q {0}".format(folder))
except Exception as e:
print("WARN: Failed to delete => {0}".format(e),file=sys.stderr)
if (path.isdir(folder)):
print("WARN: Failed to delete {0}".format(folder),file=sys.stderr)
# -------------------------------------------------------------------------------------
其他回答
import os
import stat
import shutil
def errorRemoveReadonly(func, path, exc):
excvalue = exc[1]
if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES:
# change the file to be readable,writable,executable: 0777
os.chmod(path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
# retry
func(path)
else:
# raiseenter code here
shutil.rmtree(path, ignore_errors=False, onerror=errorRemoveReadonly)
如果设置了ignore_errors,错误将被忽略;否则,如果设置了onerror,则调用它来处理带有参数(func, path, exc_info)的错误,其中func是os。listdir,操作系统。Remove, or os.rmdir;Path是导致该函数失败的参数;exc_info是由sys.exc_info()返回的元组。如果ignore_errors为false且onerror为None,则会引发异常。在这里输入代码
import shutil
shutil.rmtree(dest, ignore_errors=True)
我想添加一个“纯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上运行) 如果需要,可以进行非常细粒度的日志记录,例如,记录每一次删除。
它有助于删除包含所有文件和文件夹的目录
import os
def rrmdir(path):
for entry in os.scandir(path):
if entry.is_dir():
rrmdir(entry)
else:
os.remove(entry)
os.rmdir(path)
您可以尝试下面的代码删除文件或文件夹,而不管它们是空的还是非空的。
import shutil
import os
directory = "path/to/the/root/folder"
files_in_directory = os.listdir(directory)
for file in files_in_directory:
try:
path_to_file_or_folder = os.path.join(directory, file)
shutil.rmtree(path_to_file_or_folder)
except:
os.unlink(path_to_file_or_folder)