Answer to Question #200774 in Python for Anthony Phenomenal

Question #200774

Describe how catching exception can help with file errors. Write three python examples that actually generate file errors in your computer and catch the errors with try: except: blocks. Include the code and output for each example in your post.


1
Expert's answer
2021-05-30T13:35:45-0400
1. FileNotFoundError


raised when a file or directory is requested but doesn’t exist.
Example
try:
    file_name = 'myfile.txt'
    with open(file_name) as f:
        print(f)
except:
    print("File Not Found");




2. Exception FileExistsError


Raised when trying to create a file or directory which already exists.
Example:
import os
try:
    file_name = 'myfile.txt'
    
    os.mkdir('./myfile.txt')
except FileExistsError:
    print("File Exists Error")


choose = input('Rewrite y/n')


3. PermissionError
Raised when trying to run an operation without the adequate access rights 
Example
import os
try:
    os.mkdir('admin_data', 000)
    with open('admin_data') as f:
    
    print(f)
except PermissionError:
    print("Access denied")

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS