In order to delete a dir/folder using Python code we can make use of the below there modules,
Example 1: using os module to delete an empty directory
import os dir = "/Users/code2care/PycharmProjects/pythonProject/mydir/" if os.path.exists(dir): if len(os.listdir(dir)) != 0: print("Directory is not empty") else: os.rmdir(dir) print("Directory: " + dir + " deleted ...") else: print("Directory not found: " + dir)
Note that before deleting the directory it should be empty or else you will get OSError: [Errno 66] Directory not empty
Example 2: using shutil module to delete an non-empty directory
import shutil import os dir = "/Users/code2care/PycharmProjects/pythonProject/mydir/" if os.path.exists(dir): shutil.rmtree(dir) print("Directory: " + dir + " deleted ...") else: print("Directory not found: " + dir)
Directory: /Users/code2care/PycharmProjects/pythonProject/mydir/ deleted ...
Have Questions? Post them here!
- tkinter - Hello World! Program
- How to install Python Specific version (3.8, 3.9 or 3.10) using Brew
- How to install SpaCy (NLP Library) on Mac
- Python matplotlib segmentation fault: 11 macOS Big Sur
- How to uninstall pip Python packages
- 3 Ways to find if element is present in a List in Python
- How to Convert Python String to DateTime Object
- Python f-strings Formatted String Literals Syntax and Examples
- Where does brew install python in macOS
- Take input argument from command line in Python Programming
- Advanced print() Function Tutorial and Techniques for Python Developers
- How to add borders to tkinter label text
- Whats new in Python 3.10 Pre-release
- Float built-in function in Python
- List of All 35 Reserved Keywords in Python Programming Language 3.11
- How to check if Key Exists in Python Dictionary?
- Read a file line by line in Python Program
- ModuleNotFoundError: No module named qdarkstyle.colorsystem [Python]
- What is the Max and Minimum Value of int type in Python?
- What is Terminal Velocity and its Formula? How to calculate it programmatically?
- Fix: TypeError: can only concatenate str (not int) to str in Python
- How to take user input from the console in a Python program
- [Fix] TypeError: str object is not callable in Python
- 3 Python program to add two numbers
- How to delete a file using Python code example
- How to save webpage as pdf using macOS Safari - MacOS
- Check installed Python version in Windows, Linux & macOS - Python
- How to create Jira API Token for Atlassian Account to connect Jira Cloud REST API - Jira
- Git Commit - Author identity unknown, Please tell me who you are email - Git
- [Solved] SharePoint System.IO.FileNotFoundException was unhandled - SharePoint
- Two Ways to Extract rar (*.rar) files on Mac - MacOS
- Officially Send WhatsApp message using webpage (html) - WhatsApp
- How to Convert String to DateTime in Python - Python