Answer to Question #101080 in Python for rishabh jain

Question #101080
Describe how catching exceptions can help with file errors. Write three Python examples that actually generate file errors on your computer and catch the errors with try: except: blocks.Describe how you might deal with each error if you were writing a large production program.
1
Expert's answer
2020-01-09T06:25:39-0500

1. FileNotFoundError

raised when a file or directory is requested but doesn’t exist. Corresponds to errno ENOENT.


Describe -- I would do the same as in the code, check and ask the user to create a file or not


try:

file_name = 'some_missing_file'

with open(file_name) as f:

print(f)


except FileNotFoundError:


print(f'File: {file_name} not found')

choose = input(f'Create file {file_name} y/n \n')


if choose == 'y':

with open(file_name, 'w') as f:

print(f'File: {f} write')


else:

exit('Bye!')


2. Exception FileExistsError

Raised when trying to create a file or directory which already exists. Corresponds to errno EEXIST.


Describe -- I would do the same as in the code, check and ask the user to overwrite the file or not

import os


try:


file_name = 'some_missing_file'

os.mkdir('./some_missing_file')


except FileExistsError:

print(f'File: some_missing_file exists')

choose = input('Rewrite y/n')


if choose == 'y':

with open(file_name, 'w') as f:

print(f'File: {f} rewrite')

3. PermissionError

Raised when trying to run an operation without the adequate access rights - for example filesystem permissions.

Corresponds to errno EACCES and EPERM.


Describe -- Basically, such an error appears if not an experienced user is trying to remove or modify something, or if someone wants to read a file that should not be with this error, I don’t see the point of fighting as they only help from unnecessary actions, but as a last resort, the user can contact the system administrator


import os


try:


os.mkdir('admin_data', 000)


with open('admin_data') as f:

print(f)


except PermissionError:


print('Access denied \n'

'Ask your system administrator')


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