当我试图删除一个非空文件夹时,我得到一个“访问被拒绝”错误。我在尝试中使用了以下命令:os.remove("/folder_name")。
删除一个非空文件夹/目录最有效的方法是什么?
当我试图删除一个非空文件夹时,我得到一个“访问被拒绝”错误。我在尝试中使用了以下命令:os.remove("/folder_name")。
删除一个非空文件夹/目录最有效的方法是什么?
当前回答
import shutil
shutil.rmtree(dest, ignore_errors=True)
其他回答
你可以使用os。简单的系统命令:
import os
os.system("rm -rf dirname")
显然,它实际上调用系统终端来完成这项任务。
与操作系统。我提出的解决方案由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。
import shutil
shutil.rmtree(dest, ignore_errors=True)
十年后,在使用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,那就很方便了。
只需一些python 3.5选项就可以完成上面的回答。(我很想在这里找到它们)。
import os
import shutil
from send2trash import send2trash # (shutil delete permanently)
删除空文件夹
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")
删除包含此文件的also文件夹
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)
删除只包含.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")
删除小于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")