I use Try Catch Else Finally block to create this function.
Here is my code:
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)
<class '_io.TextIOWrapper'>
>>> out.close()
>>> os.remove("myfile.txt")
"""
try:
file_handle = open('myfile.txt', 'r')
return file_handle
except FileNotFoundError:
print('The file is not there.')
return None
else:
print('The file is there!')
finally:
print('We did something.')
However, when I run the doctest, the print statement never work in except and else block. Only the print statement in finally block is working.
I got this as result, which is not what I wanted.
>>> out = read_a_file() #while the file is not there
We did something.
Help!!! How to solve this issue?
You have to import these packages
import pandas as pd
from functools import reduce
from pathlib import Path
import os