Solution 1

def read_line_number(filepath, line_number):
    with open(filepath) as fp:
        return fp.readlines()[line_number - 1]

Nth Line from File

Write a function that receives a path to a text file and a line number as parameter, and returns the N-th line of that file.

Example:

read_line_number('test-file.txt', 2)  # "this is the line number 2"

Test Cases

test read second line - Run Test

import tempfile

def test_read_second_line():
    fp = tempfile.NamedTemporaryFile(mode="w")
    fp.write('this is line 1\n')
    fp.write('this is line 2\n')
    fp.write('this is line 3\n')
    fp.flush()

    assert read_line_number(fp.name, 2) == 'this is line 2\n'

    fp.close()

test read last line - Run Test

import tempfile

def test_read_last_line():
    fp = tempfile.NamedTemporaryFile(mode="w")
    fp.write('this is line 1\n')
    fp.write('this is line 2\n')
    fp.write('this is line 3\n')
    fp.flush()

    assert read_line_number(fp.name, 3) == 'this is line 3\n'

    fp.close()
def read_line_number(filepath, line_number): pass