import os import shutil # 笔记-删除指定文件夹和文件 def del_files(): fp = r'C:\Freqty\setting.json' dirp = r'C:\Freqty\Licenses' if os.path.exists(fp): os.remove(r'C:\Freqty\setting.json') #删除文件 print('删除setting.json成功!') else: print('待删除文件setting.json不存在!!') if os.path.exists(dirp): #方法一,简单 shutil.rmtree(r'C:\Freqty\Licenses') #递归删除目录树(不为空的文件夹) # 方法二, # def del_dir(self, path): # 删除文件夹 # for j in os.listdir(path): # path_file = os.path.join(path, j) # 取文件绝对路径 # if not os.listdir(path_file): # 判断文件如果为空 # os.removedirs(path_file) # 则删除该空文件夹,如果不为空删除会报异常 # else: # self.del_dir(path_file) print('删除Licenses文件夹成功!') else: print('待删除文件夹Licenses不存在!!') del_files()
Python删除指定文件和文件夹
最新推荐文章于 2024-07-12 16:16:27 发布