当前位置: 代码迷 >> 综合 >> 利用python快速删除指定目录下的文件和文件增夹
  详细解决方案

利用python快速删除指定目录下的文件和文件增夹

热度:81   发布时间:2024-02-27 22:27:58.0

方法一:构造函数,检查指定目录是否为空,如果不为空,使用OS和迭代删除的方法,删除test目录下的所有目录和文件,代码如下:

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'test' del_file(path)

方法二:使用pathlib,shutil,删除更加快捷。unlink()删除文件,rmtree()删除目录,一气呵成。推荐此方法

import shutil
from pathlib import Path
def  del_file(path):for elm in Path(path).glob('*'):print(elm)elm.unlink() if elm.is_file() else shutil.rmtree(elm)
if __name__ == '__main__':path=r'test' del_file(path)

 

  相关解决方案