Как найти определенное слово в файле python

The reason why you always got True has already been given, so I’ll just offer another suggestion:

If your file is not too large, you can read it into a string, and just use that (easier and often faster than reading and checking line per line):

with open('example.txt') as f:
    if 'blabla' in f.read():
        print("true")

Another trick: you can alleviate the possible memory problems by using mmap.mmap() to create a “string-like” object that uses the underlying file (instead of reading the whole file in memory):

import mmap

with open('example.txt') as f:
    s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
    if s.find('blabla') != -1:
        print('true')

NOTE: in python 3, mmaps behave like bytearray objects rather than strings, so the subsequence you look for with find() has to be a bytes object rather than a string as well, eg. s.find(b'blabla'):

#!/usr/bin/env python3
import mmap

with open('example.txt', 'rb', 0) as file, 
     mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
    if s.find(b'blabla') != -1:
        print('true')

You could also use regular expressions on mmap e.g., case-insensitive search: if re.search(br'(?i)blabla', s):

In this Python tutorial, you’ll learn to search a string in a text file. Also, we’ll see how to search a string in a file and print its line and line number.

After reading this article, you’ll learn the following cases.

  • If a file is small, read it into a string and use the find() method to check if a string or word is present in a file. (easier and faster than reading and checking line per line)
  • If a file is large, use the mmap to search a string in a file. We don’t need to read the whole file in memory, which will make our solution memory efficient.
  • Search a string in multiple files
  • Search file for a list of strings

We will see each solution one by one.

Table of contents

  • How to Search for a String in Text File
    • Example to search for a string in text file
  • Search file for a string and Print its line and line number
  • Efficient way to search string in a large text file
  • mmap to search for a string in text file
  • Search string in multiple files
  • Search file for a list of strings

How to Search for a String in Text File

Use the file read() method and string class find() method to search for a string in a text file. Here are the steps.

  1. Open file in a read mode

    Open a file by setting a file path and access mode to the open() function. The access mode specifies the operation you wanted to perform on the file, such as reading or writing. For example, r is for reading. fp= open(r'file_path', 'r')

  2. Read content from a file

    Once opened, read all content of a file using the read() method. The read() method returns the entire file content in string format.

  3. Search for a string in a file

    Use the find() method of a str class to check the given string or word present in the result returned by the read() method. The find() method. The find() method will return -1 if the given text is not present in a file

  4. Print line and line number

    If you need line and line numbers, use the readlines() method instead of read() method. Use the for loop and readlines() method to iterate each line from a file. Next, In each iteration of a loop, use the if condition to check if a string is present in a current line and print the current line and line number

Example to search for a string in text file

I have a ‘sales.txt’ file that contains monthly sales data of items. I want the sales data of a specific item. Let’s see how to search particular item data in a sales file.

sales text file
def search_str(file_path, word):
    with open(file_path, 'r') as file:
        # read all content of a file
        content = file.read()
        # check if string present in a file
        if word in content:
            print('string exist in a file')
        else:
            print('string does not exist in a file')

search_str(r'E:demosfiles_demosaccountsales.txt', 'laptop')

Output:

string exists in a file

Search file for a string and Print its line and line number

Use the following steps if you are searching a particular text or a word in a file, and you want to print a line number and line in which it is present.

  • Open a file in a read mode.
  • Next, use the readlines() method to get all lines from a file in the form of a list object.
  • Next, use a loop to iterate each line from a file.
  • Next, In each iteration of a loop, use the if condition to check if a string is present in a current line and print the current line and line number.

Example: In this example, we’ll search the string ‘laptop’ in a file, print its line along with the line number.

# string to search in file
word = 'laptop'
with open(r'E:demosfiles_demosaccountsales.txt', 'r') as fp:
    # read all lines in a list
    lines = fp.readlines()
    for line in lines:
        # check if string present on a current line
        if line.find(word) != -1:
            print(word, 'string exists in file')
            print('Line Number:', lines.index(line))
            print('Line:', line)

Output:

laptop string exists in a file
line: laptop 10 15000
line number: 1

Note: You can also use the readline() method instead of readlines() to read a file line by line, stop when you’ve gotten to the lines you want. Using this technique, we don’t need to read the entire file.

Efficient way to search string in a large text file

All above way read the entire file in memory. If the file is large, reading the whole file in memory is not ideal.

In this section, we’ll see the fastest and most memory-efficient way to search a string in a large text file.

  • Open a file in read mode
  • Use for loop with enumerate() function to get a line and its number. The enumerate() function adds a counter to an iterable and returns it in enumerate object. Pass the file pointer returned by the open() function to the enumerate().
  • We can use this enumerate object with a for loop to access the each line and line number.

Note: The enumerate(file_pointer) doesn’t load the entire file in memory, so this is an efficient solution.

Example:

with open(r"E:demosfiles_demosaccountsales.txt", 'r') as fp:
    for l_no, line in enumerate(fp):
        # search string
        if 'laptop' in line:
            print('string found in a file')
            print('Line Number:', l_no)
            print('Line:', line)
            # don't look for next lines
            break

Example:

string found in a file
Line Number: 1
Line: laptop 10 15000

mmap to search for a string in text file

In this section, we’ll see the fastest and most memory-efficient way to search a string in a large text file.

Also, you can use the mmap module to find a string in a huge file. The mmap.mmap() method creates a bytearray object that checks the underlying file instead of reading the whole file in memory.

Example:

import mmap

with open(r'E:demosfiles_demosaccountsales.txt', 'rb', 0) as file:
    s = mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ)
    if s.find(b'laptop') != -1:
        print('string exist in a file')

Output:

string exist in a file

Search string in multiple files

Sometimes you want to search a string in multiple files present in a directory. Use the below steps to search a text in all files of a directory.

  • List all files of a directory
  • Read each file one by one
  • Next, search for a word in the given file. If found, stop reading the files.

Example:

import os

dir_path = r'E:demosfiles_demosaccount'
# iterate each file in a directory
for file in os.listdir(dir_path):
    cur_path = os.path.join(dir_path, file)
    # check if it is a file
    if os.path.isfile(cur_path):
        with open(cur_path, 'r') as file:
            # read all content of a file and search string
            if 'laptop' in file.read():
                print('string found')
                break

Output:

string found

Search file for a list of strings

Sometimes you want to search a file for multiple strings. The below example shows how to search a text file for any words in a list.

Example:

words = ['laptop', 'phone']
with open(r'E:demosfiles_demosaccountsales.txt', 'r') as f:
    content = f.read()
# Iterate list to find each word
for word in words:
    if word in content:
        print('string exist in a file')

Output:

string exist in a file

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    In this article, we are going to see how to search for a string in text files using Python

    Example:

    string = “GEEK FOR GEEKS”
    Input: “FOR” 
    Output: Yes, FOR is present in the given string.

    Text File for demonstration:

    myfile.txt

    Finding the index of the string in the text file using readline()

    In this method, we are using the readline() function, and checking with the find() function, this method returns -1 if the value is not found and if found it returns 0.

    Python3

    with open(r'myfile.txt', 'r') as fp:

        lines = fp.readlines()

        for row in lines:

            word = 'Line 3'

            if row.find(word) != -1:

                print('string exists in file')

                print('line Number:', lines.index(row))

    Output:

    string exists in file
    line Number: 2

    Finding string in a text file using read()

    we are going to search string line by line if the string is found then we will print that string and line number using the read() function.

    Python3

    with open(r'myfile.txt', 'r') as file:

            content = file.read()

            if 'Line 8' in content:

                print('string exist')

            else:

                print('string does not exist')

    Output:

    string does not exist

    Search for a String in Text Files using enumerate()

    We are just finding string is present in the file or not using the enumerate() in Python.

    Python3

    with open(r"myfile.txt", 'r') as f:

        for index, line in enumerate(f):

            if 'Line 3y' in line:

                print('string found in a file')           

                break

        print('string does not exist in a file')

    Output:

    string does not exist in a file

    Last Updated :
    14 Mar, 2023

    Like Article

    Save Article

    In this article, we will learn how we can replace text in a file using python.

    Method 1: Searching and replacing text without using any external module

    Let see how we can search and replace text in a text file. First, we create a text file in which we want to search and replace text. Let this file be SampleFile.txt with the following contents:

    To replace text in a file we are going to open the file in read-only using the open() function. Then we will t=read and replace the content in the text file using the read() and replace() functions.

    Syntax: open(file, mode=’r’)

    Parameters:

    • file : Location of the file
    • mode : Mode in which you want toopen the file.

    Then we will open the same file in write mode to write the replaced content.

    Python3

    search_text = "dummy"

    replace_text = "replaced"

    with open(r'SampleFile.txt', 'r') as file:

        data = file.read()

        data = data.replace(search_text, replace_text)

    with open(r'SampleFile.txt', 'w') as file:

        file.write(data)

    print("Text replaced")

    Output:

    Text replaced

    Method 2: Searching and replacing text using the pathlib2 module

    Let see how we can search and replace text using the pathlib2 module. First, we create a Text file in which we want to search and replace text. Let this file be SampleFile.txt with the following contents:

    Install pathlib2 module using the below command:

    pip install pathlib2

    This module offers classes representing filesystem paths with semantics appropriate for different operating systems. To replace the text using pathlib2 module we will use the Path method of pathlib2 module.

    Syntax: Path(file)

    Parameters:

    • file: Location of the file you want to open

    In the below code we are replacing “dummy” with “replaced” in our text file. using the pathlib2 module. 

    Code:

    Python3

    from pathlib2 import Path

    def replacetext(search_text, replace_text):

        file = Path(r"SampleFile.txt")

        data = file.read_text()

        data = data.replace(search_text, replace_text)

        file.write_text(data)

        return "Text replaced"

    search_text = "dummy"

    replace_text = "replaced"

    print(replacetext(search_text, replace_text))

    Output:

    Text replaced

    Method 3: Searching and replacing text using the regex module

    Let see how we can search and replace text using the regex module. We are going to use the re.sub( ) method to replace the text.

    Syntax: re.sub(pattern, repl, string, count=0, flags=0)

    Parameters:

    • repl : Text you want to add
    • string : Text you want to replace

    Code:

    Python3

    import re

    def replacetext(search_text,replace_text):

        with open('SampleFile.txt','r+') as f:

            file = f.read()

            file = re.sub(search_text, replace_text, file)

            f.seek(0)

            f.write(file)

            f.truncate()

        return "Text replaced"

    search_text = "dummy"

    replace_text = "replaced"

    print(replacetext(search_text,replace_text))

    Output:

    Text replaced

    Method 4: Using fileinput

    Let see how we can search and replace text using the fileinput module. For this, we will use FileInput() method to iterate over the data of the file and replace the text.

    Syntax: FileInput(files=None, inplace=False, backup=”, *, mode=’r’)

    Parameters:

    • files : Location of the text file
    • mode : Mode in which you want toopen the file
    • inplace : If value is True then the file is moved to a backup file and
    • standard output is directed to the input file
    • backup : Extension for the backup file

    Code:

    Python3

    from fileinput import FileInput

    def replacetext(search_text, replace_text):

        with FileInput("SampleFile.txt", inplace=True,

                       backup='.bak') as f:

            for line in f:

                print(line.replace(search_text,

                                   replace_text), end='')

        return "Text replaced"

    search_text = "dummy"

    replace_text = "replaced"

    print(replacetext(search_text, replace_text))

    Output:

    Text replaced

    Last Updated :
    14 Sep, 2021

    Like Article

    Save Article

    Как осуществить поиск по ключевому слову в файле всех строк где оно присутствует?

    Есть файл, в нем несколько строк.
    Мне нужно осуществить поиск ключевого слова или фразы в файле, чтобы нашлись все строки содержащие это слово или эту фразу.
    Я знаю что это делается через библиотеку re
    Там есть re.findall(r’шаблон’, ‘текст для поиска’)
    Нужно сделать это через имя переменной. Ну например это переменная var1 и var2. Мне нужно заменить тексты в кавычках именами переменных, но как?
    И еще нужно чтобы на месте ‘текст для поиска’ было имя переменной содержащей путь к файлу, в котором нужно производить поиск. Файл текстовый. Искать нужно по всему файлу.

    Надеюсь, поможете)
    Заранее спасибо


    • Вопрос задан

      более трёх лет назад

    • 1952 просмотра

    Пригласить эксперта

    Регулярные выражения – очень мощный инструмент, а у вас совсем простая задача.

    Для вашего случая вместо re.findall лучше использовать проверку на вхождение подстроки с помощью ключевого слова in.

    with open(filename,"r") as myfile:
        for line in myfile:
            if var1 in line:
                print(line)

    Здесь вместо filename вставляете путь и имя к вашему файлу, а вместо var1 – что нужно искать.
    Ну и вместо print(line) можете делать с найденной строкой line всё, что вам нужно – например, куда-то сохранить.

    Тяжело понять. Надо на питоне?

    import re
    filename="file.txt"
    pattern="S*y{2,5}S* "
    prog = re.compile(pattern)
    with open(filename,"r") as myfile:
        for line in myfile:
            if prog.match(line):
                print(line)

    А может просто grep нужен?


    • Показать ещё
      Загружается…

    16 мая 2023, в 11:05

    800 руб./за проект

    16 мая 2023, в 11:03

    600 руб./за проект

    16 мая 2023, в 10:59

    500 руб./за проект

    Минуточку внимания

    Добавить комментарий