Access Denied when trying to delete directory with PYTHON

Asked

Viewed 1,358 times

1

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

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

When using the 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 tried running the code in administrator mode by CMD, the same error occurred. I use Windows 10.

I wonder why I’m not allowed to exclude?

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)
  • This error is common when manipulating a directory that is open on your computer.

1 answer

2


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 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 issue, since it is not allowed to remove folders with os.remove() if they are not empty.

Stay 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 done, we can attack the permission problem. In addition the folder is empty (which was solved above using rmtree), can give permission problem when have any file opened inside such a folder, or else if the user running the script does not actually have permission in windows file manager.

  • Try to close all open files and programs;
  • check the folder permissions by right-clicking on it and going into properties. See if the user who ran the program has the permission to remove the folder.
  • Thanks! The problem was using . remove() without deleting the files before, did not know that it only erased empty folders, I will test its more optimized code, and as soon as it works as a solution. Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.