21: Program to Delete File or Folder in Python


Example 1: Delete an empty folder/directory using os.rmdir()
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)
Documentation:

https://docs.python.org/3/library/os.html#os.rmdir


Note: If the directory does not exist FileNotFoundError is raised, If empty OSError is raised


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)
Documentation: https://docs.python.org/3/library/os.html#os.remove

Note: If the path is a directory, an OSError is raised.


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)
Documentation: a-link" href="https://docs.python.org/3/library/os.html#os.rmdir

Note: It deletes an entire directory tree

Delete files or folders using Python Example

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

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap