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
  Error With Reading Files In Directory And Calculating Values chascp 2 72 Feb-15-2020, 01:57 PM
Last Post: chascp
  Simple text to binary python script gmills13 2 140 Feb-04-2020, 08:44 PM
Last Post: snippsat
  Find all “*.wav” files that created yesterday on linux host with python. pydeev 6 402 Jan-07-2020, 06:43 AM
Last Post: pydeev
  index error in text script Bartry 2 182 Dec-09-2019, 11:50 AM
Last Post: Malt
  How to make a telegram bot respond to the specific word in a sentence? Metodolog 1 147 Dec-02-2019, 11:19 PM
Last Post: stullis
  error merge text files ledgreve 3 175 Nov-18-2019, 12:41 PM
Last Post: DeaD_EyE
  namedtuples and text files menator01 4 177 Nov-02-2019, 12:28 PM
Last Post: menator01
  auto supply values to a python script(function) from text file metro17 4 260 Oct-26-2019, 01:25 AM
Last Post: ichabod801
  print a word after specific word search evilcode1 8 288 Oct-22-2019, 08:08 AM
Last Post: newbieAuggie2019
  Still playing with text files (Jose Portilla on Udemy) Drone4four 2 339 Oct-17-2019, 07:20 PM
Last Post: Drone4four

Forum Jump:

Users browsing this thread: 1 Guest(s)