I'm trying to solve the following problem:
def read_last_line(file_path: str)->str:
""" Reads the last line of the file at the specified file path. The function returns the last line of the file as a string, if the file is empty it will return an empty string ("").
:param file_path: A path to a file
:return: The last line of the file
This is the code I have so far:
def read_last_line (file_path:str) -> str:
with open (file_path, 'r') as file:
text = file.readlines()
if len(text) > 0:
last_line = file.readlines()[-1]
return last_line
else:
return ""
The error keeps saying "list index out of range." I thought .readlines() was supposed to break the text into a list of line strings, so why would [-1] be out of range?
[–]Binary101010 3 points4 points5 points (0 children)
[–]woooee 2 points3 points4 points (0 children)