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)