Deleting Files in Python
Python provides built-in support for removing files and directories using
the os module. This allows your program to manage files safely
and efficiently.
Removing a File
To delete a file, first import the os module and then use the
os.remove() function.
Example: Delete a File
Checking File Existence Before Deletion
To avoid errors, it is a good practice to confirm that the file exists before deleting it.
Example: Safe File Deletion
Benefits of this approach:
-
Prevents runtime errors (like
FileNotFoundError) - Safer for real-world applications
Deleting a Folder
To remove an empty directory, use the os.rmdir() method.
