In Python, What Is The Method To Delete A File Or Folder?

To delete a file or folder in Python, you can use the os module, which provides a way to interact with the operating system. Specifically, you can use the os.remove() function to delete a file, and os.rmdir() function to delete an empty folder.

Here’s an example of how to delete a file:

import os

file_path = '/path/to/file.txt'

if os.path.exists(file_path):
    os.remove(file_path)
    print('File deleted successfully.')
else:
    print('The file does not exist.')

And here’s an example of how to delete an empty folder:

import os

folder_path = '/path/to/folder/'

if os.path.exists(folder_path):
    os.rmdir(folder_path)
    print('Folder deleted successfully.')
else:
    print('The folder does not exist.')

Note that os.rmdir() will only delete an empty folder. If the folder is not empty, you can use shutil.rmtree() function from the shutil module to delete the entire folder and its contents recursively.

import shutil

folder_path = '/path/to/folder/'

if os.path.exists(folder_path):
    shutil.rmtree(folder_path)
    print('Folder and its contents deleted successfully.')
else:
    print('The folder does not exist.')

Remember to be cautious when using file deletion operations, as they are irreversible.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!