Access Denied when trying to delete directory with PYTHON

I have several folders, and within these, several other folders, and I need to enter one by one to delete other folders (yes, they are many nested folders).

The name of the folders that I should delete have their name in the year+month format (ex.: 201808), I need to clean the folders that are 2 or more months behind (ex.: 201705, 201709, 201806).

When using os.remove(path), the program returns me an error:

Traceback (most recent call last):
  File "C:\Users\Usuario\Desktop\teste.py", line 36, in <module>
    os.remove(caminhoPastaFinal)
PermissionError: [WinError 5] Acesso negado: 'C:\\Users\\Usuario\\Desktop\\Área de testes\\pasta1\\pasta2\\pasta3\\pasta4\\201712'

I have already tried to run the code in mode administrator by CMD, the same error occurred. I use Windows 10.

I would like to know why I am not allowed to delete?

Follows the Code:

import os
from datetime import *

def verificarNome(nomePasta):
    mes=nomePasta[-2:]
    ano=nomePasta[:-2]
    if ano<anoAtual:
        return True
    elif mes<=mesAtual:
        return True
    return False


dataAtual = datetime.now()
anoAtual = str(dataAtual.year)
mesAtual = dataAtual.month
if mesAtual < 10:
    mesAtual = "0"+str(mesAtual-2)
else:
    mesAtual = str(mesAtual-2)

caminhoPai = 'C:\\Users\\Usuario\\Desktop\\Área de testes'

for caminhoPasta in os.listdir(caminhoPai): #Logo farei uma função recursiva que diminua esse código, mas ainda tenho que estudá-las
    caminhoFilho1 = caminhoPai+"\\"+caminhoPasta
    for caminhoPasta2 in os.listdir(caminhoFilho1):
        caminhoFilho2 = caminhoFilho1+"\\"+caminhoPasta2
        for caminhoPasta3 in os.listdir(caminhoFilho2):
            caminhoFilho3 = caminhoFilho2+"\\"+caminhoPasta3
            for caminhoPasta4 in os.listdir(caminhoFilho3):
                caminhoFilho4 = caminhoFilho3+"\\"+caminhoPasta4
                arrayPastasVerificar = os.listdir(caminhoFilho4)
                for pastaFinal in arrayPastasVerificar:
                    if verificarNome(pastaFinal): 
                        caminhoPastaFinal = caminhoFilho4+"\\"+pastaFinal
                        os.remove(caminhoPastaFinal)
Author: Nathan Schroeder, 2018-08-07

1 answers

First let's optimize this code:

  • instead of using os.listdir() use os.walk() because it is already automatically recursive.
  • we can also treat the folder name as a direct date using strptime.
  • another optimization is to use shutil.rmtree() to remove the folder - this function already automatically removes the contents of the folder first. This can help with the permission issue, as it is not allowed to remove folders with os.remove() if they are not empty.

Looks like this:

import os
import shutil
import datetime

este_mes = datetime.date.today().replace(day=1)
mes_passado = (este_mes - datetime.timedelta(days=1)).replace(day=1)
dois_meses_atras = (mes_passado - datetime.timedelta(days=1)).replace(day=1)

for caminho, pastas, arquivos in os.walk(caminhoPai):
    for pasta in pastas[:]:
        try:
            data_pasta = datetime.datetime.strptime(pasta, '%Y%m')
        except ValueError:
            continue
        if data_pasta < dois_meses_atras:
            pastas.remove(pasta)
            shutil.rmtree(os.path.join(caminho, pasta))

Once this is done, we can tackle the permission issue. In addition to the folder being empty (which was solved above using rmtree), it can give permission problem when you have some file open inside such a folder, or else if the user running the script does not actually have permission in windows File Manager.

  • try closing all open files and programs;
  • check the permissions of the folder by right-clicking on it and going to properties. See if the user who ran the program has permission to remove the folder.
 2
Author: nosklo, 2018-08-07 18:04:44