Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The following function openFile() attempts to open a file that does not exist, a

ID: 3928102 • Letter: T

Question

The following function openFile() attempts to open a file that does not exist, and raises a FileNotFoundError exception.

def openFile():

'open hambone.txt and read content'

infile = open( 'hambone.txt', 'r' )

content = infile.read()

infile.close()

Write a function tryOpenFile()that takes no input arguments. The function should wrap the function call to openFile() in try/except statements to handle the error, so that the program does not enter an erroneous state. When called, the function will print out the following message: "hambone.txt file could not be found"

This means you will need to include the function definition for openFile() in your module.

Test calling tryOpenFile() function in the interactive shell.

Explanation / Answer

def openFile():
   'open hambone.txt and read content'
   infile = open( 'hambone.txt', 'r' )
   content = infile.read()
   infile.close()
def tryOpenFile():
   try:
       openFile()
   except:
       print "hambone.txt file could not be found."
tryOpenFile()

# sample output

# hambone.txt file could not be found

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote