Bottom Page

Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 How to make a script to find a certain word in text files in a whole directory ?
I have not yet attempted to make this.
i browsed for 1 hour on web,could not find a single article


>Thanks in advance Pray
I have created 2 different .txt files in the directory of the script called test.txt and test2.txt
and i have written word in each file but different lines. and got the following result after executing the script:

<_io.TextIOWrapper name=[b]'test.txt'[/b] mode='r' encoding='UTF-8'>
<_io.TextIOWrapper name=[b]'test2.txt'[/b] mode='r' encoding='UTF-8'>
I have used the following libs:
from os import listdir
from os.path import isfile, join

What I did was to create a list called db = [], then I have used listdir('.') to iterate trough each item in the current directory.
after that by using endswith method if dir_.endswith('.txt'): i have been able to only read the txt files.
and then last part was to read each file and see if it was containing the word word.
with open(dir_,'r') as file_:
You don't have to search for 'how to find a single word in a bunch of files using Python'.
Do it step by step.
How to get a list of files in a given directory. click
How to open and read from a file. click
How to find a word in a string. click

Then you need to loop over each file in the list of the found files, open it, read it line by line, check for the word in each line. Print out the file name, and the line number where the word is present.
idontreallywolf likes this post
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Put all files in a directory into list. How? Denial 2 76 Yesterday, 10:05 PM
Last Post: Larz60+
  helping PyInstaller To Find files Harshil 0 162 Aug-30-2020, 10:16 AM
Last Post: Harshil
  Find specific subdir, open files and find specific lines that are missing from a file tester_V 8 508 Aug-25-2020, 01:52 AM
Last Post: tester_V
  Trying to find first 2 letter word in a list of words Oldman45 7 314 Aug-11-2020, 08:59 AM
Last Post: Oldman45
  How to extract a single word from a text file buttercup 7 351 Jul-22-2020, 04:45 AM
Last Post: bowlofred
  Complex word search multiple files Kristenl2784 0 153 Jul-18-2020, 01:22 PM
Last Post: Kristenl2784
  Find, delete and add text into pdf file a_shvechkov 2 321 Jul-08-2020, 10:50 AM
Last Post: a_shvechkov
  Outputting Sorted Text files Help charlieroberrts 1 192 Jul-05-2020, 08:37 PM
Last Post: menator01
  Python: Automated Script to Read Multiple Files in Respective Matrices Robotguy 7 526 Jul-03-2020, 01:34 AM
Last Post: bowlofred
  Make the script read from any directory falahfakhri 2 343 Jun-15-2020, 02:18 PM
Last Post: falahfakhri

Forum Jump:

Users browsing this thread: 1 Guest(s)