HOWTO · Python
How to Find String in File using Python
The tutorial demonstrates how to search for a string in a text file in Python.
On this page
To find a literal substring in a text file, use read() with in for a Boolean answer, readlines() when you need to inspect matching lines, or find() when you need a character position. For a large file or byte-oriented data, mmap provides a file-backed search. The examples use the same small text so you can compare their results and tradeoffs. Each example is runnable; the output shown below matches the supplied execution.
Search a File’s Contents with read() and in
The read() method returns the remaining file contents as one string. Use Python’s in operator to test whether that string contains the literal text you want. The expression produces True or False, which is useful when the only question is whether the substring occurs.
This approach is direct, but it reads the entire file into memory before searching. It suits small or moderate text files and cases where you also need the complete contents. If the file is too large to hold comfortably in memory, choose a line-oriented or mapped approach instead.
Run this example:
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as directory:
path = Path(directory) / "notes.txt"
path.write_text("status=ready\nowner=Sam\n", encoding="utf-8")
with path.open(encoding="utf-8") as file:
found = "ready" in file.read()
print(found)
True
Search Line by Line with readlines()
The readlines() method returns a list containing the file’s lines, including their newline characters when present. You can test each line with in and stop at the first match. This is useful when the matching line itself is relevant, such as when deciding which record to display or process.
Although the loop can stop early, readlines() has already loaded all lines into a list. Its memory use therefore grows with the file. For a large file that should be processed incrementally, iterate over the open file directly with for line in file instead; that avoids building the complete list while retaining the same line-by-line matching logic.
Run this example:
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as directory:
path = Path(directory) / "notes.txt"
path.write_text("status=ready\nowner=Sam\n", encoding="utf-8")
with path.open(encoding="utf-8") as file:
for line in file.readlines():
if "owner" in line:
print(line.rstrip())
break
owner=Sam
Use find() to Get a Match Position
Use the string find() method on the contents returned by read() when you need the starting character index rather than only a yes-or-no answer. The index is zero-based: a match at the very start returns 0, while a later match returns its position in the string. When there is no match, find() returns -1; check explicitly for that value instead of treating every result as a Boolean, because 0 is false-like in Python.
The returned position counts characters in the decoded Python string, not bytes in the file. Open text using an appropriate encoding when the file contains non-ASCII text. If you need byte offsets or the content is binary, use a byte-oriented search such as mmap with a bytes pattern.
Run this example:
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as directory:
path = Path(directory) / "notes.txt"
path.write_text("status=ready\nowner=Sam\n", encoding="utf-8")
with path.open(encoding="utf-8") as file:
contents = file.read()
position = contents.find("ready")
print(position)
print(contents.find("missing"))
7
-1
Search a Large File with mmap
The mmap module maps a file into a bytes-like object that supports searching without first creating a Python string containing the whole file. It can be useful when working with a large file, but it does not guarantee a faster search: performance depends on the file, storage, operating system, and access pattern. A mapping also uses operating-system resources, so close it when finished.
Search the mapping with a bytes pattern such as b"ready". Unlike the text examples, this checks encoded bytes and returns a byte offset. The pattern must be bytes; a normal string such as "ready" is a different type. This example uses UTF-8 bytes for the same ASCII text and opens the file in binary mode.
Run this example:
import mmap
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as directory:
path = Path(directory) / "notes.txt"
path.write_bytes(b"status=ready\nowner=Sam\n")
with path.open("rb") as file:
with mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as mapped:
print(mapped.find(b"ready"))
7
Choose the Right Approach
Choose read() with in when a Boolean answer is enough and the complete text fits comfortably in memory. Choose readlines() when you need a list of lines and want to inspect or retain them; remember that the list holds the whole file. For large text files where each line can be handled independently, iterate over the file object directly rather than storing all lines.
Choose find() when the character position of the first literal match matters. Compare its result to -1 for absence and allow 0 as a valid position. Choose mmap when a file-backed byte search is appropriate and a byte offset is useful; encode the target as bytes and do not assume that mapping will always be faster. These methods search literal text. If the task instead requires patterns, case normalization, or every occurrence, select a method designed for that requirement.