Python Practice › OS Module Programs › Program 9
Remove a folder that is not empty
Write a Python program to remove a directory that contains files.
Output
False
Approach
shutil.rmtree()deletes a folder and everything inside it.
Solution
import osimport shutil os.makedirs("full_dir/sub", exist_ok=True)open("full_dir/sub/a.txt", "w").close()shutil.rmtree("full_dir")print(os.path.exists("full_dir"))Output
False
Watch out
rmtree deletes permanently. Double-check the path before calling it.
Learn the concept
New to this topic? Read the lesson, then come back.