Bacancy Technology
Bacancy Technology represents the connected world, offering innovative and customer-centric information technology experiences, enabling Enterprises, Associates and the Society to Rise™.
12+
Countries where we have happy customers
1050+
Agile enabled employees
06
World wide offices
12+
Years of Experience
05
Agile Coaches
14
Certified Scrum Masters
1000+
Clients projects
1458
Happy customers
Artificial Intelligence
Machine Learning
Salesforce
Microsoft
SAP
January 10, 2024
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.