Select a \"wrapper\" function safeOpen() for the open()function. Recall that whe
ID: 3867093 • Letter: S
Question
Select a "wrapper" function safeOpen() for the open()function. Recall that when open() is called to open a file that doesn't exist in the current working directory, an exception is raised: > > > safeOpen('ftest.py",r') def safeOpen(filename, mode): try: infile = open(filename, mode) return infile except: return None def safeOpen(filename, mode): try: infile = open(filename, mode) return filename except: return infile def safeOpen(mode): try: infile = open (filename, mode) return infile except: return infileExplanation / Answer
def safeOpen(filename, mode):
try:
infile = open(filename, mode)
return inflie
except:
return None
safeOpen(filename, mode): - the function safeOpen receives file name ‘frest.py’ and stored it in the parameter variable filename. Mode ‘r’, for read is stored in parameter variable mode.
Exception handling mechanism starts with try:
open(filename, mode) is used to open the given file in filename variable with mode stored in mode variable.
If it is successful then it will return the infile.
If file not found and exception is generated then except: part will be executed and it will None.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.