Python Forum

Full Version: How to make a script to find a certain word in text files in a whole directory ?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have not yet attempted to make this.
i browsed for 1 hour on web,could not find a single article


Wall

>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.