Finding a value in a text file

A text file named values.txt contains one integer per line, in the order shown in Listing 2. It has no header or blank lines. All file operations succeed. The supplied helper in Listing 1 reads the file; the function in Listing 3 searches the returned lines in file order.

Listing 1: Supplied helper that reads the file and returns its lines as strings.
def read_lines(path):
    with open(
        path, "r", encoding="utf-8"
    ) as file:
        lines = file.readlines()
    return lines
Listing 2: Contents of values.txt, corresponding to eleven integer entries.
1
2
0
4
5
0
0
0
0
0
0
Listing 3: Return the zero-based position of the first matching integer, or -1 if it is absent.
def find_in_file(path, value):
    lines = read_lines(path)
    for i in range(len(lines)):
        if int(lines[i]) == value:
            return i
    return -1

print(
    find_in_file("values.txt", 5)
)

What is printed by Listing 3?

  • 4
  • 5
  • -1
  • 0
  • read_lines(path) receives the path of an existing UTF-8 text file and returns its lines in file order as a list of strings. For a separate file containing 8 and 3 on two lines, it returns ["8\n", "3\n"].
  • file.readlines() reads all remaining lines. Each string retains its ending newline, when present; a final line without one remains unchanged. An empty file returns [].
  • open(path, "r", encoding="utf-8") opens the file for reading and returns a file object. The with block closes it before read_lines returns. The returned list remains available to the caller.
  • Assume every line represents an integer, with no header or blank lines, and all file operations succeed. int("8\n") returns the integer 8.
  • find_in_file(path, value) receives the file path and the integer to find. It returns the first matching zero-based position or -1 if absent. For a separate file containing 8, 3, and 8 on three lines, searching for 8 returns 0, and searching for 9 returns -1. An empty file returns -1.
  • len(lines) counts the lines; range(stop) visits 0 through stop - 1, and range(0) is empty.
  • print(value) displays the value and a new line.