import os
"""
Deletes an empty folder at the given path.
Args:
folder_path (str): The path of the directory to be deleted.
Returns:
None
Raises:
OSError: If the folder is not empty or cannot be deleted.
"""
def delete_empty_folder(folder_path):
try:
os.rmdir(folder_path)
print(f"Folder '{folder_path}' was deleted successfully!")
except OSError as e:
print(f"Error while deleting the folder '{folder_path}': {e}")
folder_path = "d://data/" # example
delete_empty_folder(folder_path)
Example 2: Delete a file from a folder using os.remove()
import os
"""
Deletes a file from the given folder.
Args:
folder_path (str): The path of the folder containing the file.
file_name (str): The name of the file to be deleted.
Returns:
None
Raises:
OSError: If the file cannot be deleted.
"""
def delete_file_from_folder(folder_path, file_name):
try:
file_path = os.path.join(folder_path, file_name)
os.remove(file_path)
print(f"File '{file_name}' was deleted successfully from folder '{folder_path}'!")
except OSError as e:
print(f"Error while deleting file '{file_name}' from folder '{folder_path}': {e}")
folder_path = "d://data/"
file_name = "data_2023.csv"
delete_file_from_folder(folder_path, file_name)
Example 3: Delete a folder and all its files using shutil.rmtree()
import shutil
"""
Deletes a folder and all its contents.
Args:
folder_path (str): The path of the folder to be deleted.
Returns:
None
Raises:
FileNotFoundError: If the folder does not exist.
"""
def delete_folder(folder_path):
try:
shutil.rmtree(folder_path)
print(f"Folder '{folder_path}' and its contents were deleted successfully!")
except FileNotFoundError as e:
print(f"Error while deleting folder '{folder_path}': {e}")
# Example usage
folder_path = "d://data/"
delete_folder(folder_path)
Facing issues? Have Questions? Post them here! I am happy to answer!
Author Info:
Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.
Follow him on: X
You can also reach out to him via e-mail: rakesh@code2care.org
More Posts related to Python-Programs,
- Program 5: Find Sum of Two Integer Numbers - 1000+ Python Programs
- 34: Traverse a List in Reverse Order - 1000+ Python Programming
- 22: Send Yahoo! Email using smtplib - SMTP protocol client using Python Program
- 35: Python Program to find the System Hostname
- 27: Measure Elapsed Time for a Python Program Execution
- Program 7: Find Difference of Two Numbers - 1000+ Python Programs
- Program 12: Calculate Area and Circumference of Circle - 1000+ Python Programs
- Program 9: Divide Two Numbers - 1000+ Python Programs
- Program 2: Print your name using print() function - 1000+ Python Programs
- 25: How to rename a file using Python Program
- 17: Find Factorial of a Number - 1000+ Python Programs
- Program 6: Find Sum of Two Floating Numbers - 1000+ Python Programs
- 23: Python Programs to concatenate two Lists
- 36: Python Program Convert Hex String to Integer
- 20 - Python - Print Colors for Text in Terminal - 1000+ Python Programs
- Python Program: Use NumPy to generate a random number between 0 and 1
- 32: Python Program to Find Square Root of a Number
- Program 8: Multiply Two Numbers - 1000+ Python Programs
- Program 11: Calculate Percentage - 1000+ Python Programs
- 18: Get Sub List By Slicing a Python List - 1000+ Python Programs
- 28: Program to Lowercase a String in Python
- Program 1: Print Hello World! - 1000+ Python Programs
- 21: Program to Delete File or Folder in Python
- 29: Program to convert Python dict to dataframe
- 33: Python Program to find the current time in India (IST)
More Posts:
- What is Terminal Velocity and its Formula? How to calculate it programmatically? - Python
- How to uninstall Rust Language from Mac/Linux/Ubuntu - Rust
- [Fix] Notepad Error: Windows cannot access the specified Device or Path - Windows-11
- Android : java.lang.IllegalArgumentException File contains a path separator - Android
- MongoDB Hello World! Example - 2022
- Fix: Unsupported Java. Your build is currently configured to use Java 17.0.5 and Gradle 7.1. - Gradle
- AADSTS90033: A transient error has occurred. Please try again. [Microsoft 365] - Microsoft
- How to reset Mac Password using Terminal - MacOS