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
Check File Existence Before Deleting
To avoid errors (like a
FileNotFoundError), it’s a highly recommended best practice to confirm that the file exists
before attempting to remove it.
Example: Safe File Deletion
- Prevents runtime errors
- Safer for real-world applications
Deleting a Folder
To remove an empty directory, use the
os.rmdir()
method. (Note: If the folder contains files, this method will fail. You
would need the
shutil.rmtree()
method to delete non-empty folders).
