Goal: Function that will read a specific line in a .txt file.
Example .txt file used is five lines long with each line stating "First line", "Second Line", and so on down to "Firth Line".
The function I have so far will read the line as indicated by the line_number
argument when 0, 1, 2, 3, 4 is passed through it, but results in an index error
if the argument is any integer >=5 since these are blank/empty on the .txt file. I would like the function to return "Empty Line"
when a line_number
argument is used that would read a blank/empty line.
Function:
def txtfile_line(file_path: str,line_number: int):
open_file = open(file_path)
read_file = open_file.readlines()
if read_file[line_number] == '\n':
return ("Empty Line")
else:
return read_file[line_number]
print(txtfile_line("file.txt",5))
Current Output IndexError: list index out of range
if the argument entered is a blank line
Goal Output "Empty Cell"
if the argument entered is a blank line
.txt file used:
First line
Second line
Third line
Fourth line
Fifth line