当我试图删除一个非空文件夹时,我得到一个“访问被拒绝”错误。我在尝试中使用了以下命令:os.remove("/folder_name")。
删除一个非空文件夹/目录最有效的方法是什么?
当我试图删除一个非空文件夹时,我得到一个“访问被拒绝”错误。我在尝试中使用了以下命令:os.remove("/folder_name")。
删除一个非空文件夹/目录最有效的方法是什么?
当前回答
你可以使用os。简单的系统命令:
import os
os.system("rm -rf dirname")
显然,它实际上调用系统终端来完成这项任务。
其他回答
import shutil
shutil.rmtree(dest, ignore_errors=True)
基于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")
import shutil
shutil.rmtree('/folder_name')
标准库参考:shutil.rmtree。
根据设计,rmtree在包含只读文件的文件夹树上失败。如果您希望删除文件夹而不管它是否包含只读文件,请使用
shutil.rmtree('/folder_name', ignore_errors=True)
你可以使用os。简单的系统命令:
import os
os.system("rm -rf dirname")
显然,它实际上调用系统终端来完成这项任务。
您可以尝试下面的代码删除文件或文件夹,而不管它们是空的还是非空的。
import shutil
import os
directory = "path/to/the/root/folder"
files_in_directory = os.listdir(directory)
for file in files_in_directory:
try:
path_to_file_or_folder = os.path.join(directory, file)
shutil.rmtree(path_to_file_or_folder)
except:
os.unlink(path_to_file_or_folder)