To delete a file in Python is to use the pathlib module, which provides an object-oriented interface for file system paths. Here’s an example:
Deleting a File using pathlib:

from pathlib import Path

file_path = Path('path/to/your/file.txt')

try:
    file_path.unlink()
    print(f"File '{file_path}' deleted successfully.")
except FileNotFoundError:
    print(f"Error: File '{file_path}' not found.")
except Exception as e:
    print(f"Error: {e}")

Deleting a Folder (Directory) using pathlib:

from pathlib import Path
folder_path = Path('path/to/your/folder')
try:
	folder_path.rmdir()
	print(f"Folder '{folder_path}' deleted successfully.")
except FileNotFoundError:
	print(f"Error: Folder '{folder_path}' not found.")
except OSError as e:
	print(f"Error: {e}")

In the above solution use the unlink() method for files and the rmdir() method for directories in the pathlib module. The exception handling is used to catch specific errors such as files or folders not found. Adjust the paths accordingly based on your file system structure.

Support On Demand!

Python