Handling PermissionError Exception in Python file handling program
Write a Python program that opens a file and handles a PermissionError exception if there is a permission issue.
exception PermissionError:
Raised when trying to run an operation without the adequate access rights - for example filesystem permissions. Corresponds to errno EACCES, EPERM, and ENOTCAPABLE.
Sample Solution:
Code:
# Define a function named open_file that takes a filename as a parameter.
def open_file(filename):
try:
# Attempt to open the specified file in write mode ('w') using a 'with' statement.
with open(filename, 'w') as file:
# Try to read the contents of the file, but this code will not be executed because the file is opened in write mode.
contents = file.read()
# Print a message to indicate that the file contents will be displayed (this will not happen).
print("File contents:")
# Print the contents of the file (this will not happen).
print(contents)
except PermissionError:
# Handle the exception if there is a permission denied error while opening the file.
print("Error: Permission denied to open the file.")
# Usage
# Prompt the user to input a file name and store it in the 'file_name' variable.
file_name = input("Input a file name: ")
# Call the open_file function with the provided file name, attempting to open the file in write mode.
open_file(file_name)
Explanation:
In the above exercise,
- The "open_file()" function takes a filename parameter representing the name of the file to be opened.
- Inside the function, there is a try block that attempts to open the file using the open function in the write mode ('w'). The with statement automatically handles file closing.
- However, immediately after opening the file, it is attempted to read its contents using the read method. This is not valid because the file was opened in write mode, which does not allow reading.
- If the code reaches the except block, it means there was a PermissionError while opening the file due to a permission issue. In that case, an error message is printed indicating that permission is denied to open the file.
- In the example usage section, the user is prompted to input a file name. The "open_file()" function is then called with the provided file name as an argument.
Output:
Enter the file name: employees.csv Error: Permission denied to open the file.
Flowchart:
Previous: Handling TypeError Exception in Python numeric input program.
Next: Handling IndexError Exception in Python list operation program.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics