Delete Folder Access denied
当我使用了以下命令:os.remove("/folder_name")删除非空文件夹时,我收到“Access denied”错误。
删除非空文件夹/目录的最有效方法是什么?
import shutil
shutil.rmtree('/folder_name')
标准库参考:shutil.rmtree。
按照文档,rmtree删除包含只读文件的文件夹会失败。如果要删除文件夹而不管它是否包含只读文件,请使用
shutil.rmtree('/folder_name', ignore_errors=True)
参考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))
import shutil
shutil.rmtree(dest, ignore_errors=True)
在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
页:
[1]