How to Check If a String Is in a File Using Python

In this tutorial, we’ll learn how to check if a specific string exists in a file using Python. We’ll explore the simple functionality built into Python that allows us to read files, search through them, and perform actions based on whether or not we find the string.

This is a fundamental aspect of working with files and data in Python and can be applied in various problem-solving scenarios like data analysis, log monitoring, and more.

Step 1: Opening the File

Firstly, we need to open the file to read its content. Python inbuilt open() function is used for this, which accepts the filename as its argument. Here’s how to do it:

In the above line of code, “example.txt” is the name of our file, and “r” is the mode specifying that we’re opening the file for reading.

Let’s assume our ‘example.txt’ file contains the following text:

Hello world!
This is a simple text file.
We're just testing Python functionality.

Step 2: Reading the File’s Content

After opening the file, we need to read its content. The read() function is used for this:

This will read the entire content of the file and store it in the ‘content’ variable.

Step 3: Checking for the String

Now that we’ve read the content of the file, we can check for the existence of our string. This is done using the in keyword:

This code segment checks if the string “simple” is in the content of our text file. If it is, it prints “String found!”. If not, it prints “String not found!”.

Full Code

Here’s the complete code:

Output

String found!

Conclusion

Working with files and searching for specific data within them is a staple operation in many programming and data analysis tasks. As demonstrated, Python makes this process straightforward and easy to understand with its simple, inbuilt functions like open() and read().

Being able to verify the presence of a specific string in a file can be particularly useful for tasks like log analysis, data validation, and many more.