当我试图删除一个非空文件夹时,我得到一个“访问被拒绝”错误。我在尝试中使用了以下命令:os.remove("/folder_name")。
删除一个非空文件夹/目录最有效的方法是什么?
当我试图删除一个非空文件夹时,我得到一个“访问被拒绝”错误。我在尝试中使用了以下命令:os.remove("/folder_name")。
删除一个非空文件夹/目录最有效的方法是什么?
当前回答
十年后,在使用Python 3.7和Linux时,仍然有不同的方法来做到这一点:
import subprocess
from pathlib import Path
#using pathlib.Path
path = Path('/path/to/your/dir')
subprocess.run(["rm", "-rf", str(path)])
#using strings
path = "/path/to/your/dir"
subprocess.run(["rm", "-rf", path])
本质上,它使用Python的子进程模块来运行bash脚本$ rm -rf '/path/to/your/dir,就像使用终端来完成相同的任务一样。它不是完全的Python,但它完成了。
我加入pathlib的原因。路径示例是因为根据我的经验,它在处理许多路径变化时非常有用。导入pathlib的额外步骤。路径模块和将最终结果转换为字符串通常是一个较低的成本,我的开发时间。如果Path.rmdir()带有一个arg选项来显式地处理非空dirs,那就很方便了。
其他回答
从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('/folder_name')
标准库参考:shutil.rmtree。
根据设计,rmtree在包含只读文件的文件夹树上失败。如果您希望删除文件夹而不管它是否包含只读文件,请使用
shutil.rmtree('/folder_name', ignore_errors=True)
如果你不想使用shutil模块,你可以使用os模块。
from os import listdir, rmdir, remove
for i in listdir(directoryToRemove):
os.remove(os.path.join(directoryToRemove, i))
rmdir(directoryToRemove) # Now the directory is empty of files
def deleteDir(dirPath):
deleteFiles = []
deleteDirs = []
for root, dirs, files in os.walk(dirPath):
for f in files:
deleteFiles.append(os.path.join(root, f))
for d in dirs:
deleteDirs.append(os.path.join(root, d))
for f in deleteFiles:
os.remove(f)
for d in deleteDirs:
os.rmdir(d)
os.rmdir(dirPath)
如果你确定你想要删除整个目录树,并且不再对目录的内容感兴趣,那么爬行整个目录树是愚蠢的…只需从python中调用本机操作系统命令即可。它将更快,更有效,更少的内存消耗。
RMDIR c:\blah /s /q
例如*那晚尼克斯。
rm -rf /home/whatever
在python中,代码看起来像..
import sys
import os
mswindows = (sys.platform == "win32")
def getstatusoutput(cmd):
"""Return (status, output) of executing cmd in a shell."""
if not mswindows:
return commands.getstatusoutput(cmd)
pipe = os.popen(cmd + ' 2>&1', 'r')
text = pipe.read()
sts = pipe.close()
if sts is None: sts = 0
if text[-1:] == '\n': text = text[:-1]
return sts, text
def deleteDir(path):
"""deletes the path entirely"""
if mswindows:
cmd = "RMDIR "+ path +" /s /q"
else:
cmd = "rm -rf "+path
result = getstatusoutput(cmd)
if(result[0]!=0):
raise RuntimeError(result[1])