Deleting folders in python recursively

前端 未结 10 2112
梦毁少年i
梦毁少年i 2020-12-04 08:51

I\'m having a problem with deleting empty directories. Here is my code:

for dirpath, dirnames, filenames in os.walk(dir_to_search):
    //other codes

    try         


        
10条回答
  •  不知归路
    2020-12-04 09:28

    Here is a recursive solution:

    def clear_folder(dir):
        if os.path.exists(dir):
            for the_file in os.listdir(dir):
                file_path = os.path.join(dir, the_file)
                try:
                    if os.path.isfile(file_path):
                        os.unlink(file_path)
                    else:
                        clear_folder(file_path)
                        os.rmdir(file_path)
                except Exception as e:
                    print(e)
    

提交回复
热议问题