Access Denied when trying to delete directory with PYTHON

0

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

The name of the folders I want to delete are named in the year + month format (eg 201808), I need to clean folders that are 2 months or more behind (eg 201705, 201709, 201806).

When using os.remove(path) , the program returns 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've tried to run the code in administrator mode by CMD, the same error occurred. I use Windows 10.

Would you like to know why I'm not allowed to delete?

Follow 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)
    
asked by anonymous 07.08.2018 / 15:33

1 answer

1

First let's optimize this code:

  • instead of using os.listdir() use os.walk() because it is already automatically recursive.
  • In addition we can 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 may help with the permission problem since it is not allowed to remove folders with os.remove() if they are not empty.

It 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 attack the permission problem. While the folder is empty (which has been resolved above using rmtree ), it may give permission problem when there is any file open inside a folder of these, or else if the user who is running the script does not actually have permission on the windows files.

  • Try closing all open files and programs;
  • Check the permissions of the folder by right-clicking it and going to Properties. See if the user running the program has permission to remove the folder.
07.08.2018 / 17:16