In Python, you can delete files or folders using the os
and shutil
modules.
1. Deleting a File
To delete a file, use os.remove()
or pathlib.Path.unlink()
.
2. Deleting an Empty Folder
To delete an empty folder, use os.rmdir()
.
3. Deleting a Folder and Its Contents
To delete a folder along with its contents, use shutil.rmtree()
.
4. Using pathlib
for Folder Deletion (Python 3.4+)
For deleting empty folders, you can also use pathlib.Path.rmdir()
.
- Note: Ensure the file or folder is not in use before attempting to delete it.