Working with Files: Delete a File in Python
Python's core principle is to make coding easy and developers must not feel the hassle of it. To improve this, Python has a function to delete files in the code itself so that the developer need not to manually delete them.
Till now, in this 'working with files' module, you have learned the following:
- Read from a text file in Python
- Write to a text file in Python
- Create a new text file in Python
- Check if a file exists in Python
- Read CSV files in Python
- Write CSV files in Python
- Rename a file in Python
And in this article, you will be learning to delete a file in Python. Without further ado, let's get started.
Procedure to Delete a File in Python:
Let's go through the process of deleting a file in Python step by step:
- Import the 'os' module:
>>> import os
- Specify the file path and name:
>>> file_path = "path/to/file.txt"
- Delete the file using 'os.remove()':
>>> os.remove(file_path)
- Handle any exceptions: If the file specified by file_path does not exist, the 'os.remove()' function will raise a 'FileNotFoundError' exception. You can handle this exception using a try-except block to gracefully handle the situation. Here's an example of how you can do it:
>>> try:
>>> os.remove(file_path)
>>> print("File deleted successfully.")
>>> except FileNotFoundError:
>>> print("File not found.")
>>> except PermissionError:
>>> print("Permission denied. Unable to delete the file.")
This code will catch the specific exceptions raised when a file is not found or when there are permission issues. You can customize the error messages or add more specific exception handling as needed.
Conclusion:
In conclusion, deleting a file in Python is a simple task but you have to remember to give the necessary permissions to modify files in the specified directory. Make sure to exercise caution when deleting files especially if there is sensitive data in them. It is best to double-check the file path to ensure you are deleting the intended file. If you have any questions or doubts, feel free to contact us.