To search a file for a string using Python, you can use the read() function and use the Python in operator to check each line for a particular string.
string = "word"
in_file = False
with open("example.txt","r") as f:
if string in f.read():
in_file = True
print(in_file)
#Output:
True
When working with files in Python, the ability to easily search files for specific text can be valuable.
To search a file for a string in Python, we can use the Python read() function to read the entire file and use the Python in operator to check if a string is in the file.
Below is a simple example of how you can search a file for a string using Python.
string = "word"
in_file = False
with open("example.txt","r") as f:
if string in f.read():
in_file = True
print(in_file)
#Output:
True
How to Search File for String and Return Location in Python
If you want to search a file for a string and return the line number and line position, we can make a slight adjustment to our code from above.
First, we need to loop over all lines and keep track of the line number.
Then, we can use the Python find() function to find the position of first occurrence of a string in each line.
Below is an example showing how you can search a file for a string and return where the string was found in Python.
string = "word"
line_count = 0
with open("example.txt","r") as f:
for line in f:
if line.find(string) > 0:
print(line_count, line.find(string))
line_count = line_count + 1
#Output:
1 20
Hopefully this article has been useful for you to learn how to search a file for a string using Python.