Solution 1

def which_line(filepath, a_string):
    with open(filepath) as fp:
        read_data = fp.readlines()
        for line_num, line in enumerate(read_data):
            if a_string in line:
                return line_num + 1
        return None

Find Line with String

Write a function that receives a file path and a string as parameters, and
returns the line number where that string is in the file. If the string
is not in the file, it should return None.

Example:

which_line('file1.txt', 'hello world')  # 10
which_line('file1.txt', 'this is not in the file')  # None

Test Cases

test string not present - Run Test

import tempfile

def test_string_not_present():
    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 which_line(fp.name, 'foobar') == None

    fp.close()

test string present - Run Test

import tempfile

def test_string_present():
    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 which_line(fp.name, 'this is line 2') == 2
    
    fp.close()
def which_line(filepath, a_string): pass