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 with the fact 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, which means that 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 Python programming language.

First and foremost, assuming that you have installed the latest version of Python (Python 3.9.1) on your machine and have an IDE/editor to write code.

Before you jump to the next step ahead, you should know what a file is!

A file is a contagious set of bytes that saves data. This data is embodied in a particular format. Text files, images, executable files are examples of different types of files.

 

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, 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 on, 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 pretend you have to 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 have a 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!

How to Exit While loops in Python
Previous
4 Ways How to Exit While Loops in Python
How To Fade Out Audio in Canva Update
Next
How to Fade Out Audio in Canva