当我尝试删除非空文件夹时,我收到"访问被拒绝"错误.我在尝试中使用了以下命令:os.remove("/folder_name").
删除/删除非空文件夹/目录的最有效方法是什么?
dda*_*daa 1265
import shutil
shutil.rmtree('/folder_name')
Run Code Online (Sandbox Code Playgroud)
按照设计,rmtree在包含只读文件的文件夹树上失败.如果要删除文件夹而不管它是否包含只读文件,请使用
shutil.rmtree('/folder_name', ignore_errors=True)
Run Code Online (Sandbox Code Playgroud)
kku*_*sik 131
从Python文档上os.walk():
# 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))
Run Code Online (Sandbox Code Playgroud)
Siv*_*adi 105
import shutil
shutil.rmtree(dest, ignore_errors=True)
Run Code Online (Sandbox Code Playgroud)
yot*_*ota 19
从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 dir content, remove this line
Run Code Online (Sandbox Code Playgroud)
哪个pth是pathlib.Path实例.不错,但可能不是最快的.
此示例显示如何在Windows上删除某些文件的只读位设置的目录树.它使用onerror回调清除readonly位并重新尝试删除.任何后续故障都会传播.
Run Code Online (Sandbox Code Playgroud)import os, stat import shutil def remove_readonly(func, path, _): "Clear the readonly bit and reattempt the removal" os.chmod(path, stat.S_IWRITE) func(path) shutil.rmtree(directory, onerror=remove_readonly)
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)
Run Code Online (Sandbox Code Playgroud)
如果设置了ignore_errors,则忽略错误; 否则,如果设置了onerror,则调用它来处理带有参数的错误(func,path,exc_info),其中func是os.listdir,os.remove或os.rmdir; path是导致它失败的那个函数的参数; 和exc_info是sys.exc_info()返回的元组.如果ignore_errors为false且onerror为None,则会引发异常.请输入此处的代码
十年后,使用 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])
Run Code Online (Sandbox Code Playgroud)
本质上,它使用 Python 的 subprocess 模块来运行 bash 脚本$ rm -rf '/path/to/your/dir,就像使用终端来完成相同的任务一样。它不完全是Python,但它已经完成了。
我之所以包含这个pathlib.Path示例,是因为根据我的经验,它在处理许多变化的路径时非常有用。导入模块并将最终结果转换为字符串的额外步骤pathlib.Path通常可以降低我的开发时间成本。Path.rmdir()如果带有 arg 选项来显式处理非空目录会很方便。
我想添加一个“纯路径库”方法:
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()
Run Code Online (Sandbox Code Playgroud)
这依赖于Path可排序的事实,较长的路径总是在较短的路径之后排序,就像str. 因此,目录将出现在文件之前。如果我们颠倒排序,文件就会出现在它们各自的容器之前,所以我们可以简单地将它们一一取消链接/rmdir。
好处:
pathlibPython 3.6中的承诺;上面没有说明不能在 Windows 上运行的操作)如果你确定,你想要删除整个目录树,并且对dir的内容不再感兴趣,那么爬行整个目录树就是愚蠢......只需从python调用本机OS命令就可以了.它将更快,更高效,更少内存消耗.
RMDIR c:\blah /s /q
Run Code Online (Sandbox Code Playgroud)
或者*nix
rm -rf /home/whatever
Run Code Online (Sandbox Code Playgroud)
在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])
Run Code Online (Sandbox Code Playgroud)
根据kkubasik的回答,删除之前检查文件夹是否存在,更可靠
import shutil
def remove_folder(path):
# check if folder exists
if os.path.exists(path):
# remove if exists
shutil.rmtree(path)
else:
# throw your exception to handle this special scenario
raise XXError("your exception")
remove_folder("/folder_name")
Run Code Online (Sandbox Code Playgroud)
只需一些python 3.5选项即可完成上述答案.(我很想在这里找到它们).
import os
import shutil
from send2trash import send2trash # (shutil delete permanently)
Run Code Online (Sandbox Code Playgroud)
删除文件夹,如果为空
root = r"C:\Users\Me\Desktop\test"
for dir, subdirs, files in os.walk(root):
if subdirs == [] and files == []:
send2trash(dir)
print(dir, ": folder removed")
Run Code Online (Sandbox Code Playgroud)
如果它包含此文件,也删除它
elif subdirs == [] and len(files) == 1: # if contains no sub folder and only 1 file
if files[0]== "desktop.ini" or:
send2trash(dir)
print(dir, ": folder removed")
else:
print(dir)
Run Code Online (Sandbox Code Playgroud)
删除文件夹,如果它只包含.srt或.txt文件
elif subdirs == []: #if dir doesn’t contains subdirectory
ext = (".srt", ".txt")
contains_other_ext=0
for file in files:
if not file.endswith(ext):
contains_other_ext=True
if contains_other_ext== 0:
send2trash(dir)
print(dir, ": dir deleted")
Run Code Online (Sandbox Code Playgroud)
删除文件夹,如果其大小小于400kb:
def get_tree_size(path):
"""Return total size of files in given path and subdirs."""
total = 0
for entry in os.scandir(path):
if entry.is_dir(follow_symlinks=False):
total += get_tree_size(entry.path)
else:
total += entry.stat(follow_symlinks=False).st_size
return total
for dir, subdirs, files in os.walk(root):
If get_tree_size(dir) < 400000: # ? 400kb
send2trash(dir)
print(dir, "dir deleted")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
591471 次 |
| 最近记录: |