zoukankan      html  css  js  c++  java
  • 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)
     
       
           
     
          
     
     
  • 相关阅读:
    centos crash debug
    go get Unknown SSL protocol error in connection to gopkg.in
    Tensorflow serving with Kubernetes
    Spring 集成 Swagger UI
    Docker Registry V2 Garbage Collection
    Docker Registry V2 with Nginx
    Zabbix磁盘性能监控
    Zabbix CPU utilization监控参数
    Windows挂载Gluster复制卷
    Redis持久化存储(三)
  • 原文地址:https://www.cnblogs.com/dwtt/p/7772639.html
Copyright © 2011-2022 走看看