Python Forum
Searching for specific word in text files.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Searching for specific word in text files.
#1
How do I search in a file for a specific word? It should ignore word containing that word, for example.

word to search = 'ello'
text file -
hello
there
It shouldn't output anything file with the above text file
hello
ello
there
It should output 'success' with the above text file. How could I do this?
Reply
#2
my_string = "hello\nthere"
print(my_string)

start_index = my_string.find("ello")
print(start_index)

start_index = my_string.find("x")
print(start_index)
Opening files in text-mode for reading: https://docs.python.org/3/library/functions.html#open
Together with Context-Manager: https://realpython.com/working-with-file...as-pattern

All together in a function:

def has_pattern(file, pattern):
    with open(file, encoding="utf8") as fd:
        # inside this block the file is open for reading
        # read content -> find pattern -> return result_of_pattern != -1
        return fd.read().find(pattern) != -1
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Replace a text/word in docx file using Python Devan 4 2,858 Oct-17-2023, 06:03 PM
Last Post: Devan
  Color a table cell based on specific text Creepy 11 1,857 Jul-27-2023, 02:48 PM
Last Post: deanhystad
  splitting file into multiple files by searching for string AlphaInc 2 816 Jul-01-2023, 10:35 PM
Last Post: Pedroski55
  Help replacing word in Mutiple files. (SOLVED) mm309d 0 797 Mar-21-2023, 03:43 AM
Last Post: mm309d
  python print all files which contain specific word in it mg24 5 1,188 Jan-27-2023, 11:20 AM
Last Post: snippsat
  python move specific files from source to destination including duplicates mg24 3 1,051 Jan-21-2023, 04:21 AM
Last Post: deanhystad
  azure TTS from text files to mp3s mutantGOD 2 1,638 Jan-17-2023, 03:20 AM
Last Post: mutantGOD
  delete all files which contains word sql_Table1 mg24 2 824 Sep-15-2022, 10:05 PM
Last Post: mg24
  Writing into 2 text files from the same function paul18fr 4 1,629 Jul-28-2022, 04:34 AM
Last Post: ndc85430
  Delete empty text files [SOLVED] AlphaInc 5 1,511 Jul-09-2022, 02:15 PM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020