Delete multiple folders in Python

3

They could advise me, I have the following problem. I have thousands of folders which in turn has several sub-folders, there is specifically a sub-folder that is named "0".

Example:

├ DISCO_1 (CARPETA_Principal)
|  ├─ 2014353(SUB-CARPETA)
      -(SUB-Carpeta"0") #[Carpeta que se desea borrar]

|  ├─ 2014354 (SUB-CARPETA)
      -(SUB-Carpeta"0") #[Carpeta que se desea borrar]

|  └─ 2014355 (SUB-CARPETA)
      -(SUB-Carpeta"0") #[Carpeta que se desea borrar]

This is a folder that does not interest me and what I want is to delete all these sub-folders "0"

I know what it is with:

import shutil
shutil.rmtree('C:\Test\')

How could I do it?

    
asked by Armando 19.01.2016 в 20:04
source

1 answer

2

Since you are using Python 2, you can do something very similar to the answer that I gave to the question < a href="https://es.stackoverflow.com/q/2056/100"> How to manage to delete certain files of several folders in Python? using os.walk and fnmatch .

Having as an example structure:

carpeta
│── subcarpeta1
│   │── 0
│   │   │── 0.txt
│   │── 1
│   │── 2
│── subcarpeta2
│   │── 0
│   │   │── 0.txt
│   │── 1
│   │── 2
│── 0
│   │── 0.txt

You can use something like this:

import fnmatch
import os
import shutil

ruta = 'C:\Test\'
for raiz, directorios, archivos in os.walk(ruta):
    for directorio in fnmatch.filter(directorios, '0'):
        # Es necesario hacer un join con la raiz
        shutil.rmtree(os.path.join(raiz, directorio))

Result:

carpeta
│── subcarpeta1
│   │── 1
│   │── 2
│── subcarpeta2
│   │── 1
│   │── 2
    
answered by 19.01.2016 / 20:28
source