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 my pure pathlib recursive directory unlinker:
from pathlib import Path
def rmdir(directory):
directory = Path(directory)
for item in directory.iterdir():
if item.is_dir():
rmdir(item)
else:
item.unlink()
directory.rmdir()
rmdir(Path("dir/"))
The default behavior of os.walk()
is to walk from root to leaf. Set topdown=False
in os.walk()
to walk from leaf to root.
For Linux users, you can simply run the shell command in a pythonic way
import os
os.system("rm -r /home/user/folder_name")
where rm
stands for remove and -r
for recursively
Try shutil.rmtree:
import shutil
shutil.rmtree('/path/to/your/dir/')
better to use absolute path and import only the rmtree function
from shutil import rmtree
as this is a large package the above line will only import the required function.
from shutil import rmtree
rmtree('directory-absolute-path')
Try rmtree()
in shutil from the Python standard library