我是靠谱客的博主 甜美航空,这篇文章主要介绍python删除指定目录下的所有文件和目录代码,现在分享给大家,希望可以做个参考。

利用了os的remove还有递归函数调用:

import os
import shutil
def  del_file(path):
      if not os.listdir(path):
            print('目录为空!')
      else:
            for i in os.listdir(path):
                  path_file = os.path.join(path,i)  #取文件绝对路径
                  print(path_file)
                  if os.path.isfile(path_file):
                        os.remove(path_file)
                  else:
                        del_file(path_file)
                        shutil.rmtree(path_file)
if __name__ == '__main__':
      path=r'c:UsersHPdesktop1' 
      del_file(path)

定义函数,先判断是否为空,然后先删除文件,再递归删除文件夹

最后

以上就是甜美航空最近收集整理的关于python删除指定目录下的所有文件和目录代码的全部内容,更多相关python删除指定目录下内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(58)

评论列表共有 0 条评论

立即
投稿
返回
顶部