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

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

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

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

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


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

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

    • 1947 просмотров

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

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

    Для вашего случая вместо 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 нужен?


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

    15 мая 2023, в 16:15

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

    15 мая 2023, в 16:06

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

    15 мая 2023, в 15:23

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

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

    In this article, we will learn to search and replace a text of a file in Python. We will use some built-in functions and some custom codes as well. We will replace text, or strings within a file using mentioned ways.

    Python provides multiple built-in functions to perform file handling operations. Instead of creating a new modified file, we will search a text from a file and replace it with some other text in the same file. This modifies the file with new data. This will replace all the matching texts within a file and decreases the overhead of changing each word. Let us discuss some of the mentioned ways to search and replace text in a file in Python.

    Sample Text File

    We will use the below review.text file to modify the contents.

    In the movie Ghost
    the joke is built on a rock-solid boundation
    the movie would still work played perfectly straight
    The notion of a ghost-extermination squad taking on 
    the paramal hordes makes a compelling setup for a big-budget adventure of any stripe
    Indeed, the film as it stands frequently allows time to pass without a gag
    But then comes the punch line: the characters are funny
    And because we’ve been hooked by the story, the humor the characters provide is all the richer.

    Example: Use replace() to Replace a Text within a File

    The below example uses replace() function to modify a string within a file. We use the review.txt file to modify the contents. It searches for the string by using for loop and replaces the old string with a new string.

    open(file,'r') – It opens the review.txt file for reading the contents of the file.

    strip() – While iterating over the contents of the file, strip() function strips the end-line break.

    replace(old,new) – It takes an old string and a new string to replace its arguments.

    file.close() – After concatenating the new string and adding an end-line break, it closes the file.

    open(file,'w') – It opens the file for writing and overwrites the old file content with new content.

    reading_file = open("review.txt", "r")
    
    new_file_content = ""
    for line in reading_file:
        stripped_line = line.strip()
        new_line = stripped_line.replace("Ghost", "Ghostbusters")
        new_file_content += new_line +"n"
    reading_file.close()
    
    writing_file = open("review.txt", "w")
    writing_file.write(new_file_content)
    writing_file.close()

    Output:

    Example: Replace a Text using Regex Module

    An alternative method to the above-mentioned methods is to use Python’s regex module. The below example imports regex module. It creates a function and passed a file, an old string, and a new string as arguments. Inside the function, we open the file in both read and write mode and read the contents of the file.

    compile() – It is used to compile a regular expression pattern and convert it into a regular expression object which can then be used for matching.

    escape()It is used to escape special characters in a pattern.

    sub()It is used to replace a pattern with a string.

    #importing the regex module
    import re
    
    #defining the replace method
    def replace(filePath, text, subs, flags=0):
        with open(file_path, "r+") as file:
            #read the file contents
            file_contents = file.read()
            text_pattern = re.compile(re.escape(text), flags)
            file_contents = text_pattern.sub(subs, file_contents)
            file.seek(0)
            file.truncate()
            file.write(file_contents)
    
        
    file_path="review.txt"
    text="boundation"
    subs="foundation"
    #calling the replace method
    replace(file_path, text, subs)

    Output:

    FileInput in Python

    FileInput is a useful feature of Python for performing various file-related operations. For using FileInput, fileinput module is imported. It is great for throwaway scripts. It is also used to replace the contents within a file. It performs searching, editing, and replacing in a text file. It does not create any new files or overheads.

    Syntax-

    FileInput(filename, inplace=True, backup='.bak')

    Parameters-

    backup – The backup is an extension for the backup file created before editing.

    Example: Search and Replace a Text using FileInput and replace() Function

    The below function replaces a text using replace() function.

    import fileinput
    
    filename = "review.txt"
    
    with fileinput.FileInput(filename, inplace = True, backup ='.bak') as f:
        for line in f:
            if("paramal" in line):
                print(line.replace("paramal","paranormal"), end ='')
            else:
                print(line, end ='') 

    Output:

    Conclusion

    In this article, we learned to search and replace a text, or a string in a file by using several built-in functions such as replace(), regex and FileInput module. We used some custom codes as well. We saw outputs too to differentiate between the examples. Therefore, to search and replace a string in Python user can load the entire file and then replaces the contents in the same file instead of creating a new file and then overwrite the file.

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