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

python 3 fix the function import pandas as pd from functools import reduce from

ID: 3893080 • Letter: P

Question

python 3 fix the function

import pandas as pd
from functools import reduce
from pathlib import Path
import os

In this question, you have a function called read_a_file. If you try running it, it will fail due to a file not found error and will not react how we want it to react. Fix this code so that it works as expected based on the doctests, using a Try, catch, else, finally block.

def read_a_file():
"""
>>> out = read_a_file() #while the file is not there
The file is not there.
We did something.
>>> print(out)
None
>>> Path('myfile.txt').touch()
>>> out = read_a_file() #while the file is there
The file is there!
We did something.
>>> type(out)

>>> out.close()
>>> os.remove("myfile.txt")
"""
file_handle = open('myfile.txt', 'r')
return file_handle

Explanation / Answer

def read_a_file():
   try:
     file_handle = open('myfile.txt','r')
     return file_handle
   except:
     print("File is not there")
     return None