当我试图删除一个非空文件夹时,我得到一个“访问被拒绝”错误。我在尝试中使用了以下命令:os.remove("/folder_name")。
删除一个非空文件夹/目录最有效的方法是什么?
当我试图删除一个非空文件夹时,我得到一个“访问被拒绝”错误。我在尝试中使用了以下命令:os.remove("/folder_name")。
删除一个非空文件夹/目录最有效的方法是什么?
当前回答
对于Windows,如果目录不是空的,并且你有只读文件或者你会得到这样的错误
访问被拒绝 该进程无法访问该文件,因为它正被另一个进程使用
试试这个,os。system('rmdir /S /Q "{}"'.format(directory))
它相当于Linux/Mac中的rm -rf。
其他回答
删除一个文件夹,即使它可能不存在(避免Charles Chow回答中的竞态条件),但当其他事情出错时仍然有错误(例如权限问题,磁盘读取错误,文件不是目录)
对于Python 3.x:
import shutil
def ignore_absent_file(func, path, exc_inf):
except_instance = exc_inf[1]
if isinstance(except_instance, FileNotFoundError):
return
raise except_instance
shutil.rmtree(dir_to_delete, onerror=ignore_absent_file)
Python 2.7的代码几乎是一样的:
import shutil
import errno
def ignore_absent_file(func, path, exc_inf):
except_instance = exc_inf[1]
if isinstance(except_instance, OSError) and \
except_instance.errno == errno.ENOENT:
return
raise except_instance
shutil.rmtree(dir_to_delete, onerror=ignore_absent_file)
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,则会引发异常。在这里输入代码
基于递归的纯pathlib解决方案:
from pathlib import Path
def remove_path(path: Path):
if path.is_file() or path.is_symlink():
path.unlink()
return
for p in path.iterdir():
remove_path(p)
path.rmdir()
支持Windows和符号链接
与操作系统。我提出的解决方案由3个一行Python调用组成:
python -c "import sys; import os; [os.chmod(os.path.join(rs,d), 0o777) for rs,ds,fs in os.walk(_path_) for d in ds]"
python -c "import sys; import os; [os.chmod(os.path.join(rs,f), 0o777) for rs,ds,fs in os.walk(_path_) for f in fs]"
python -c "import os; import shutil; shutil.rmtree(_path_, ignore_errors=False)"
第一个脚本是chmod的所有子目录,第二个脚本是chmod的所有文件。然后第三个脚本移除所有障碍。
我已经从Jenkins作业中的“Shell脚本”中测试了这一点(我不想将新的Python脚本存储到SCM中,这就是为什么搜索一行解决方案),它适用于Linux和Windows。
在我的情况下,删除的唯一方法是使用所有的可能性,因为我的代码应该运行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)
# -------------------------------------------------------------------------------------