python 小练习之删除文件夹下的所有文件,包括子文件夹中的文件

先屡一下思路 一步步怎么实现 

1  要求是要删除所有文件(只是删除文件 而不是文件夹),所以 我们肯定要遍历这个文件目录 (for  in遍历)

2 每遍历一个元素时(文件),我们要判断该元素的属性是文件还是文件夹  (os.path.isfile(path))引入os模块

3 判断如果是文件,直接删除;如果是文件夹,继续遍历并判断。 if

代码:

import os

path = 'D:\PycharmProjects\test'
for i in os.listdir(path):
   path_file = os.path.join(path,i)  // 取文件路径
   if os.path.isfile(path_file):
      os.remove(path_file)
  else:
     for f in os.listdir(path_file):  
     path_file2 =os.path.join(path_file,f)
     if os.path.isfile(path_file2):
     os.remove(path_file2)
 
补充完善:
   上面写的方法还是有缺点的  只能删除到第二层文件夹  如果第二层文件夹里面还有文件的话  就出来不了了 
在此修改下代码  设计一个方法 然后递归去处理:
  def  del_file(path):
      for i in os.listdir(path):
         path_file = os.path.join(path,i)  // 取文件绝对路径
         if os.path.isfile(path_file):
           os.remove(path_file)
         else:
             del_file(path_file)
 
   
       
 
      
 
 
原文地址:https://www.cnblogs.com/dwtt/p/7772639.html