I\'m having a problem with deleting empty directories. Here is my code:
for dirpath, dirnames, filenames in os.walk(dir_to_search):
//other codes
try
Here's another pure-pathlib solution, but without recursion:
from pathlib import Path
from typing import Union
def del_empty_dirs(base: Union[Path, str]):
base = Path(base)
for p in sorted(base.glob('**/*'), reverse=True):
if p.is_dir():
p.chmod(0o666)
p.rmdir()
else:
raise RuntimeError(f'{p.parent} is not empty!')
base.rmdir()
Here is a recursive solution:
def clear_folder(dir):
if os.path.exists(dir):
for the_file in os.listdir(dir):
file_path = os.path.join(dir, the_file)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
else:
clear_folder(file_path)
os.rmdir(file_path)
except Exception as e:
print(e)
Just for the next guy searching for a micropython solution, this works purely based on os (listdir, remove, rmdir). It is neither complete (especially in errorhandling) nor fancy, it will however work in most circumstances.
def deltree(target):
print("deltree", target)
for d in os.listdir(target):
try:
deltree(target + '/' + d)
except OSError:
os.remove(target + '/' + d)
os.rmdir(target)
The command (given by Tomek) can't delete a file, if it is read only. therefore, one can use -
import os, sys
import stat
def del_evenReadonly(action, name, exc):
os.chmod(name, stat.S_IWRITE)
os.remove(name)
if os.path.exists("test/qt_env"):
shutil.rmtree('test/qt_env',onerror=del_evenReadonly)