[python学习篇] [os模块] [2]删除文件夹

    def deleteDirectory(self,current_path):
        if not os.path.exists(current_path):
            self.logger.info(current_path + "does not exist, go on")
            return
        assert os.path.isdir(current_path), current_path + " is not directory"
        current_filelist = os.listdir(current_path)
        for f in current_filelist:
            real_path = os.path.join(current_path,f)
            if os.path.isdir(real_path):
                real_folder_path = real_path
                try:
                    for root,dirs,files in os.walk(real_folder_path):
                        for name in files:
                            del_file = os.path.join(root,name)
                            os.remove(del_file)
                    shutil.rmtree(real_folder_path)
                except Exception,e:traceback.print_exc()
                # shutil.rmtree(real_folder_path)
            elif os.path.isfile(real_path):
                try:
                    os.remove(real_path)
                except Exception,e:
                    traceback.print_exc()
        try:
            os.rmdir(current_path) # 不加这一行,就是删除目录下的所有文件和子目录
        except Exception,e:
            traceback.print_exc()

 

posted @ 2017-06-02 09:33  liuzhipenglove  阅读(698)  评论(0编辑  收藏  举报