简体   繁体   中英

Python function that will read a specific line in a .txt file

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

Wrong indexing -->

sample file im using:

1
2
3
4
5
def txtfile_line(file_path: str,line_number: int):
    open_file = open(file_path)
    read_file = open_file.readlines()
    if line_number > len(read_file):
        return ("invalid index")
    if read_file[line_number-1] == '\n':
        return ("Empty Line")
    else:
        return read_file[line_number - 1]

print(txtfile_line("file.txt",5))
5

when running print(txtfile_line("file.txt",6)) this modified function will give

invalid index

remember that list indexes start at 0, so a list with a length of 5 would actually be indexed 0-4!

Hmm, well the code you gave me works as is. Remember that the line number starts at 0 not 1. You could be inputting a line that actually isn't there.

Also you'll want to change this:

if read_file[line_number] == "\\n": #Double backslash lets the compiler know its not a special character.
     ...

EDIT: I see, I misread the question. Here's a simple fix:

if len(read_file) <= line_number:
    return ("Empty Line")
def read_txt_line(file_path: str, line_number: int) -> str:
    try:
        open_file = open(file_path)
        read_file = open_file.readlines()
        return "Empty Line" if read_file[line_number - 1] == '\n' else read_file[line_number - 1]
    except IndexError:
        return "Empty Line"
    except FileNotFoundError as file_error:
        return str(file_error)


# Case 1 : wrong file
print(read_txt_line("data/testm.txt", 6))
# output : [Errno 2] No such file or directory: 'data/testm.txt'

# Case 2 : correct
print(read_txt_line("data/test.txt", 5))
# output : Fifth line

# Case 3 : line number beyond text file content
print(read_txt_line("data/test.txt", 6))
# output : Empty Line

test.txt file content

First line
Second line
Third line
Fourth line
Fifth line 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM