Python彻底删除文件夹及其子文件方式

苏见山
苏见山
发布时间:2026-10-13 | 5人浏览过
原创

本文介绍Python中彻底删除文件夹及其子文件的实现方式。通过结合os.walk遍历文件并修改权限,再使用shutil.rmtree清理目录,可有效解决Windows下因只读属性导致的删除失败问题。

Python彻底删除文件夹及其子文件方式

直接展示实现代码。


#coding:utf-8
import os
import stat
import shutil

#filePath:文件夹路径
def delete_file(filePath):
 if os.path.exists(filePath):
  for fileList in os.walk(filePath):
   for name in fileList[2]:
    os.chmod(os.path.join(fileList[0],name), stat.S_IWRITE)
    os.remove(os.path.join(fileList[0],name))
  shutil.rmtree(filePath)
  return "delete ok"
 else:
  return "no filepath"
 
print os.path.exists("E:\\biancheng\\python\\ascas") 
print delete_file("E:\\biancheng\\python\\ascas")

以上关于Python彻底删除文件夹及其子文件的内容即为分享的全部信息,旨在提供参考,欢迎大家支持。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表