• 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)
     
       
           
     
          
     
     
  • 相关阅读:
    codeforces 407B Long Path
    CodeForces 489C Given Length and Sum of Digits...
    hacker cup 2015 Round 1 解题报告
    hacker cup 2015 资格赛
    Codeforces 486(#277 Div 2) 解题报告
    POJ 3468 A Simple Problem with Integers splay
    Codeforces 484(#276 Div 1) D Kindergarten DP
    求平均值问题201308031210.txt
    I love this game201308022009.txt
    QQ
  • 原文地址:https://www.cnblogs.com/dwtt/p/7772639.html
Copyright © 2020-2023  润新知