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)
Output:
Directory: /Users/code2care/PycharmProjects/pythonProject/mydir/ deleted ...
More Posts related to Python,
- Comments in Python Programming
- tkinter - Hello World! Program
- How to install Python 3.11 on Mac
- Python matplotlib segmentation fault: 11 macOS Big Sur
- Change label (text) color in tkinter
- Python Hello World! Program with code example (snippet)
- Calculate discount amount python code
- Take input argument from command line in Python Programming
- How to pip install Python Modules in VSCode
- Tkinter - add x and y padding to label text
- Python raise error with message example
- Check if String Contains a Substring - Python
- Python Program To Calculate Simple Interest (SimpleInterest.py)
- What does b prefix before a String mean in Python?
- What is Terminal Velocity and its Formula? How to calculate it programmatically?
- How to List all Packages installed using pip [Python]
- Convert Float to String in Python
- Change the background of Tkinter label or text
- How to Install Python Modules in VS Code
- Indent Python code in Notepad++
- Validate email address in Python using regular expression (regex)
- Python: Fix command not found pip or pip3 on zsh shell
- TypeError: must be str, not int [Fix Python]
- ModuleNotFoundError: No module named qdarkstyle.colorsystem [Python]
- Python - Convert float to String
More Posts:
- How to enable missing SharePoint Site Assets, Site Pages library App - SharePoint
- Easy Steps to Upgrade iPhone to the new iOS 16 - HowTos
- Install postgres Client using apt-get command - Ubuntu
- Open Docker Desktop from macOS Terminal - Docker
- How to Connect to AWS Windows EC2 UI Instance from M1 Mac (Updated 2022) - HowTos
- Rename a directory using Linux/Unix command - Linux
- Merge-SPlogfile PowerShell - SharePoint Correlation ID error - SharePoint
- How to send email from JavaScript HTML using mailto - JavaScript