Skip to Content

How to Find a String in a Text File Using Python

How to Find a String in a Text File Using Python

Most developers agree that Python is one of the most influential and beloved programming languages of the present time. Python is a dynamic, high-level, open-source, and interpreted programming language.

It allows object-oriented programming as well as procedural-oriented programming.

Many students in the development field start their programming journey with Python.

 

Strings in Python

In Python, strings have the type str.  A string in Python language represents the sequence of characters. Python strings are immutable, meaning they cannot be changed or modified once created.

When you want to change or modify a string, it can not be done with the existing string; you must create a new string. This article will help you learn how to find a string in a text file using the Python programming language.

Before you start with this tutorial, please make sure that you have the latest version of Python installed on your machine. You should also have an IDE/editor ready on your computer to write code. 

 

How to find a string in a text file using Python

I am splitting the task into two different ways. First, you will learn how you can find a specific string from a text file using Python, and then I will show you how to find multiple strings with their corresponding line number.

 

1. Finding a string from a text file

 

def check(my_file, string_search):
 # Opens my_file in read only mode
 with open(my_file, 'r') as read:
 # Read all the line in the file one by one
 for line in read:
 # Checki every lines if it contains the desired
string
 if string_search in line:
 return True
 return False

 

In the above example, the check function takes two arguments: the file’s path and the desired string. Later, it opens the text file named my_file and iterates over each line sequentially.

If the line contains your desired string, it returns “True” immediately; if no line contains the desired string it returns “False.”

Now, let’s assume you have a text file called demo.text with the below text lines, and you are looking for the string ’Adam.’

 

This is a demo line
I am looking for a string
That contains Adam
Thank you!

 

Let’s pretend you must check whether this file contains the string ‘Adam’ or not. To do so, let us write the below code.

 

if check('demo.txt', 'Adam'):
 print('True')
else:
 print('Sorry String not found in your given file').

 

Using this code, you will get the output “True” because you have the string ‘Adam’ available in your text file.

 

2. Finding a string that is available in multiple lines along with the line numbers

Let’s look at a different script that might come in handy when trying to find a string in a text file.

def search_string(file_name, string_search):
# Searches for a string that available in multiple lines
along with the line numbers
x = 0 # Line number
y = [] # List of serched result
# Opens the file in read only mode
with open(my_file, 'r') as read:
 for line in read:
 x += 1
 if string_search in line:
 y.append((x, line.rstrip()))
return y

 

Let’s shed some light on the algorithm of the above Python program. First and foremost, this program accepts two arguments as well: the file’s path and the desired string.

Later on, it creates an empty list of tuples y. Then again, it opens the file in read-only mode and iterates over each line sequentially to get the desired string.

If it finds the string in a line, it creates a tuple of line number & the line and, adds that to a list of tuples, and returns the list of tuples. Now assume your text file has the below lines:

 

I am Adam
Demo line 1
Demo line 2
Adam writes the code
Thank you!

 

You can get all the lines along with the line numbers for the given string ‘Adam’ by writing the code below.

 

get_lines = search_string('demo.txt', 'Adam')
print('Lines with the String : ', len(get_lines))
for elem in get_lines:
print('Line Number = ', elem[0], ' : Line = ', elem[1])

 

You should get an output like this:

 

Lines with the String: 2
Line Number = 1 : Line = I am Adam
Line Number = 4 : Line = Adam writes the code

 

Conclusion

File handling skills are essential as a Python developer. Developers often need to access and manipulate data in files, whether reading from them or writing into them.

I hope this article will help you to find strings in a text file using Python.

Happy coding!