如何移除/删除不为空的文件夹?

2022-09-05 01:09:00

当我尝试删除不为空的文件夹时,我收到“访问被拒绝”错误。我在尝试中使用了以下命令:.os.remove("/folder_name")

删除/删除不为空的文件夹/目录的最有效方法是什么?


答案 1
import shutil

shutil.rmtree('/folder_name')

标准库参考:shutil.rmtree

根据设计,在包含只读文件的文件夹树上失败。如果希望删除文件夹,而不管它是否包含只读文件,请使用rmtree

shutil.rmtree('/folder_name', ignore_errors=True)

答案 2

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))