¿Cómo puedo eliminar / eliminar una carpeta que no está vacía con Python?


Recibo un error de 'acceso denegado' cuando intento eliminar una carpeta que no está vacía. Usé el siguiente comando en mi intento: os.remove("/folder_name").

¿Cuál es la forma más efectiva de eliminar/eliminar una carpeta/directorio que no está vacía?

 691
Author: Sinister Beard, 2008-11-19

15 answers

import shutil

shutil.rmtree('/folder_name')

Standard Library Reference: shutil.rmtree .

Por diseño, rmtree falla en los árboles de carpetas que contienen archivos de solo lectura. Si desea que la carpeta se elimine independientemente de si contiene archivos de solo lectura, use

shutil.rmtree('/folder_name', ignore_errors=True)
 1105
Author: ddaa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-23 12:04:08

De los documentos de python en os.walk():

# Delete everything reachable from the directory named in 'top',
# assuming there are no symbolic links.
# CAUTION:  This is dangerous!  For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files in os.walk(top, topdown=False):
    for name in files:
        os.remove(os.path.join(root, name))
    for name in dirs:
        os.rmdir(os.path.join(root, name))
 122
Author: kkubasik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-20 20:00:13
import shutil
shutil.rmtree(dest, ignore_errors=True)
 98
Author: Siva Mandadi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-07 00:59:15

Desde python 3.4 puedes usar:

import pathlib

def delete_folder(pth) :
    for sub in pth.iterdir() :
        if sub.is_dir() :
            delete_folder(sub)
        else :
            sub.unlink()
    pth.rmdir() # if you just want to delete dir content, remove this line

Donde pth es una instancia pathlib.Path. Bonito, pero puede que no sea el más rápido.

 15
Author: yota,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-07 06:52:15
import os
import stat
import shutil

def errorRemoveReadonly(func, path, exc):
    excvalue = exc[1]
    if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES:
        # change the file to be readable,writable,executable: 0777
        os.chmod(path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)  
        # retry
        func(path)
    else:
        # raiseenter code here

shutil.rmtree(path, ignore_errors=False, onerror=errorRemoveReadonly) 

Si ignore_errors está establecido, los errores son ignorados; de lo contrario, si onerror está establecido, se llama para manejar el error con argumentos (func, path, exc_info) donde func es os.listdir, os.quitar, o os.rmdir; path es el argumento de la función que causó que fallara; y exc_info es una tupla devuelta por sys.exc_info (). Si ignore_errors es false y onerror es None, se genera una excepción.introduzca el código aquí

 8
Author: RongyanZheng,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-20 00:49:38

Si está seguro de que desea eliminar todo el árbol de dir, y ya no está interesado en el contenido del dir, entonces rastrear todo el árbol de dir es estupidez... simplemente llame al comando nativo del sistema operativo desde python para hacer eso. Será más rápido, eficiente y consumirá menos memoria.

RMDIR c:\blah /s /q 

O * nix

rm -rf /home/whatever 

En python, el código se verá como..

import sys
import os

mswindows = (sys.platform == "win32")

def getstatusoutput(cmd):
    """Return (status, output) of executing cmd in a shell."""
    if not mswindows:
        return commands.getstatusoutput(cmd)
    pipe = os.popen(cmd + ' 2>&1', 'r')
    text = pipe.read()
    sts = pipe.close()
    if sts is None: sts = 0
    if text[-1:] == '\n': text = text[:-1]
    return sts, text


def deleteDir(path):
    """deletes the path entirely"""
    if mswindows: 
        cmd = "RMDIR "+ path +" /s /q"
    else:
        cmd = "rm -rf "+path
    result = getstatusoutput(cmd)
    if(result[0]!=0):
        raise RuntimeError(result[1])
 6
Author: P M,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-12 11:49:50

Basado en la respuesta de kkubasik, compruebe si existe la carpeta antes de eliminar, más robusto

import shutil
def remove_folder(path):
    # check if folder exists
    if os.path.exists(path):
         # remove if exists
         shutil.rmtree(path)
remove_folder("/folder_name")
 5
Author: Charles Chow,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-06 21:07:20

De docs.python.org:

Este ejemplo muestra cómo eliminar un árbol de directorios en Windows donde algunos de los archivos tienen su bit de solo lectura establecido. Utiliza el onerror devolución de llamada para borrar el bit de solo lectura y volver a intentar eliminar. Cualquier el fallo posterior se propagará.

import os, stat
import shutil

def remove_readonly(func, path, _):
    "Clear the readonly bit and reattempt the removal"
    os.chmod(path, stat.S_IWRITE)
    func(path)

shutil.rmtree(directory, onerror=remove_readonly)
 4
Author: Dave Chandler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-11 11:39:26

Si no quieres usar el módulo shutil puedes usar el módulo os.

from os import listdir, rmdir, remove
for i in listdir(directoryToRemove):
    os.remove(os.path.join(directoryToRemove, i))
rmdir(directoryToRemove) # Now the directory is empty of files
 4
Author: Byron Filer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-11 05:37:45

Solo algunas opciones de python 3.5 para completar las respuestas anteriores. (Me hubiera encantado encontrarlos aquí).

import os
import shutil
from send2trash import send2trash # (shutil delete permanently)

Eliminar carpeta si está vacía

root = r"C:\Users\Me\Desktop\test"   
for dir, subdirs, files in os.walk(root):   
    if subdirs == [] and files == []:
           send2trash(dir)
           print(dir, ": folder removed")

Eliminar también carpeta si contiene este archivo

    elif subdirs == [] and len(files) == 1: # if contains no sub folder and only 1 file 
        if files[0]== "desktop.ini" or:  
            send2trash(dir)
            print(dir, ": folder removed")
        else:
            print(dir)

Eliminar carpeta si solo contiene .srt or .archivo (s) txt

    elif subdirs == []: #if dir doesn’t contains subdirectory
        ext = (".srt", ".txt")
        contains_other_ext=0
        for file in files:
            if not file.endswith(ext):  
                contains_other_ext=True
        if contains_other_ext== 0:
                send2trash(dir)
                print(dir, ": dir deleted")

Eliminar carpeta si su tamaño es inferior a 400kb:

def get_tree_size(path):
    """Return total size of files in given path and subdirs."""
    total = 0
    for entry in os.scandir(path):
        if entry.is_dir(follow_symlinks=False):
            total += get_tree_size(entry.path)
        else:
            total += entry.stat(follow_symlinks=False).st_size
    return total


for dir, subdirs, files in os.walk(root):   
    If get_tree_size(dir) < 400000:  # ≈ 400kb
        send2trash(dir)
    print(dir, "dir deleted")
 3
Author: JinSnow,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-28 15:07:56

Puede usar el sistema operativo.comando del sistema para simplificar:

import os
os.system("rm -rf dirname")

Como es obvio, en realidad invoca a system terminal para realizar esta tarea.

 1
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-11 04:46:15

Para eliminar una carpeta incluso si no existe (evitando la condición de carrera en La respuesta de Charles Chow ) pero aún tiene errores cuando otras cosas salen mal (por ejemplo, problemas de permisos, error de lectura del disco, el archivo no es un directorio)

Para Python 3.x:

import shutil

def ignore_absent_file(func, path, exc_inf):
    except_instance = exc_inf[1]
    if isinstance(except_instance, FileNotFoundError):
        return
    raise except_instance

shutil.rmtree(dir_to_delete, onerror=ignore_absent_file)

El código de Python 2.7 es casi el mismo:

import shutil
import errno

def ignore_absent_file(func, path, exc_inf):
    except_instance = exc_inf[1]
    if isinstance(except_instance, OSError) and \
        except_instance.errno == errno.ENOENT:
        return
    raise except_instance

shutil.rmtree(dir_to_delete, onerror=ignore_absent_file)
 1
Author: Eponymous,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-28 17:53:09
def deleteDir(dirPath):
    deleteFiles = []
    deleteDirs = []
    for root, dirs, files in os.walk(dirPath):
        for f in files:
            deleteFiles.append(os.path.join(root, f))
        for d in dirs:
            deleteDirs.append(os.path.join(root, d))
    for f in deleteFiles:
        os.remove(f)
    for d in deleteDirs:
        os.rmdir(d)
    os.rmdir(dirPath)
 1
Author: amazingthere,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-03 08:24:56

He encontrado una manera muy fácil de Eliminar cualquier carpeta (Incluso NO Vacía) o archivo en WINDOWS OS.

os.system('powershell.exe  rmdir -r D:\workspace\Branches\*%s* -Force' %CANDIDATE_BRANCH)
 1
Author: seremet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-01 15:29:47

Con os.caminando me gustaría proponer la solución que consta de 3 one-liner Python llamadas:

python -c "import sys; import os; [os.chmod(os.path.join(rs,d), 0o777) for rs,ds,fs in os.walk(_path_) for d in ds]"
python -c "import sys; import os; [os.chmod(os.path.join(rs,f), 0o777) for rs,ds,fs in os.walk(_path_) for f in fs]"
python -c "import os; import shutil; shutil.rmtree(_path_, ignore_errors=False)"

El primer script chmod es all sub-directories, el segundo script chmod es all files. Entonces el tercer guión elimina todo sin impedimentos.

He probado esto desde el "Shell Script" en un trabajo de Jenkins (no quería almacenar un nuevo script de Python en SCM, por eso busqué una solución de una línea) y funcionó para Linux y Windows.

 1
Author: Alexander Samoylov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-23 15:32:36