How to remove a directory in Python using os.rmdir() or shutil.rmtree()?
Published on Aug. 22, 2023, 12:17 p.m.
To remove a directory in Python, you can use either the os.rmdir() or the shutil.rmtree() function, depending on whether the directory is empty or not.
If the directory to be deleted is empty, you can use os.rmdir(path) to remove it:
import os
dir_path = '/path/to/empty_directory'
if os.path.exists(dir_path):
os.rmdir(dir_path)
If the directory has contents and needs to be deleted along with all its contents, you can use shutil.rmtree(path) to remove it:
import shutil
dir_path = '/path/to/non_empty_directory'
if os.path.exists(dir_path):
shutil.rmtree(dir_path)
Note that both functions will raise an exception if the specified directory doesn’t exist, so you may want to check for its existence using os.path.exists(path)
beforehand.
Also, be careful when using shutil.rmtree()
as it will delete all files and subdirectories of the specified directory. Be sure to double-check your path before calling this function to avoid accidental data loss.