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

Python create function openAndReturnLast3() to meet the conditions below # - acc

ID: 3721592 • Letter: P

Question

Python

create function openAndReturnLast3() to meet the conditions below

# - accept 1 string parameter; the name of a file

# - add a docstring

# - use exception handling techniques to attempt to open the filename

# provided, if it does not exist, return False

# - the file will contain an unknown number of lines (at least 3)

# - store the last 3 lines of the file in a single string var

# --- ensure to strip the newline character from the lines

# --- e.g. "line one" + "line two" + "line three" will be

# "line oneline twoline three"

# - return the resultant string var

Explanation / Answer

def openAndReturnLast3(filename):
with open(filename) as fp:
try:
content = fp.readlines()[-3:]
content = [c[:-1] for c in content]
result = "".join(content)
return result
except : # whatever reader errors you care about
return False

# copy pastable code: https://paste.ee/p/vpTef