Python has a lot of built-in libraries can help to delete folders and files, when faced with the need to delete multiple non-empty folders, and the directory hierarchy is more than 3 layers above, only one built-in method is not able to completely delete the folder and the effect of the file, compared to the low way is multiple calls until deleted. However, we can combine multiple built-in library functions to delete a non-empty folder at a time, regardless of how deep its directory hierarchy is.
Import osimport shutilimport tracebackimport globalvardef misc_init () # Clean the test Result folder # get the Curre NT Path Current_path = Os.path.split (Os.path.realpath (__file__)) [0] # Some folder not delete Except_folders = Glo Balvar. Except_folders # Get the folder uder current path current_filelist = Os.listdir (Current_path) for F in Current_f Ilelist:if Os.path.isdir (f): If f in except_folders:continue else: Real_folder_path = Os.path.join (Current_path, f) try:for root, dirs, files in OS. Walk (Real_folder_path): For name in Files: # Delete the log and test res Ult Del_file = os.path.join (root, name) Os.remove (del_file) Logger.info (' Remove file[%s] successfully '% del_file) Shutil.rmtree (Real_folder_pat H Logger.info (' Remove foler[%s] successfully '% real_folder_path) except Exception, E: Traceback.print_exc ()
Main steps:
1. Use Os.listdir to list the folders under the current path and, if necessary, to skip folders that you do not want to delete
2, using Os.walk can recursively traverse the files in the current path folder, using Os.remove to delete files
3. Use Shutil.retree to remove these empty folders recursively
Note: The idea is to remove all files from the file directory tree first, and then delete the empty folders recursively. Globalvar is a custom global variable file, not a Python library
Python implementation to completely delete files under Folders and folders