M11) 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.
What is printed by Listing 3?
45-10
TipHint
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 containing8and3on 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. Thewithblock closes it beforeread_linesreturns. 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 integer8. find_in_file(path, value)receives the file path and the integer to find. It returns the first matching zero-based position or-1if absent. For a separate file containing8,3, and8on three lines, searching for8returns0, and searching for9returns-1. An empty file returns-1.len(lines)counts the lines;range(stop)visits0throughstop - 1, andrange(0)is empty.print(value)displays the value and a new line.