In: Computer Science
Python Coding
Create function openAndReturnLastN() to meet the conditions below
- accept 2 parameters; 1 string (name of a file) and 1 integer
(N)
- 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
- store the last N lines of the file in a single string var
- return the resultant string var
--- ensure to strip the newline character from the lines
--- e.g. textfile:
--- e.g. "line one\n"
--- "line two\n"
--- "line three\n"
--- "line four\n"
--- "line five\n"
--- integer: 2
--- e.g. "line four" + "line five" will be "line fourline
five"
- params: string, integer
- return: string
def openAndReturnLastN(filename,N):
"""
write the docstring whatever needded your wish
accept 2 parameters; 1 string (name of a file) and 1 integer
(N)
- add a docstring
- use exception handling techniques to attempt to open the filename
provided, if it does not exist,
return False/string
"""
string=""
try:#try to open the file
with open(filename,'r') as file:
#for the last N lines
for line in (file.readlines()[-N:]):
#strip the \n and add to string
string+=line.strip("\n")
#return the stripped string
return string
except:#exception catching
print("cannot able to open file")
return False
print(openAndReturnLastN("abc.txt",2))
comment if any doubts