Deleting folders in python recursively

前端 未结 10 2080
梦毁少年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:27

    Here's another pure-pathlib solution, but without recursion:

    from pathlib import Path
    from typing import Union
    
    def del_empty_dirs(base: Union[Path, str]):
        base = Path(base)
        for p in sorted(base.glob('**/*'), reverse=True):
            if p.is_dir():
                p.chmod(0o666)
                p.rmdir()
            else:
                raise RuntimeError(f'{p.parent} is not empty!')
        base.rmdir()
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-12-04 09:30

    Just for the next guy searching for a micropython solution, this works purely based on os (listdir, remove, rmdir). It is neither complete (especially in errorhandling) nor fancy, it will however work in most circumstances.

    def deltree(target):
        print("deltree", target)
        for d in os.listdir(target):
            try:
                deltree(target + '/' + d)
            except OSError:
                os.remove(target + '/' + d)
    
        os.rmdir(target)
    
    0 讨论(0)
  • 2020-12-04 09:31

    The command (given by Tomek) can't delete a file, if it is read only. therefore, one can use -

    import os, sys
    import stat
    
    def del_evenReadonly(action, name, exc):
        os.chmod(name, stat.S_IWRITE)
        os.remove(name)
    
    if  os.path.exists("test/qt_env"):
        shutil.rmtree('test/qt_env',onerror=del_evenReadonly)
    
    0 讨论(0)
提交回复
热议问题