Apr-27-2017, 09:14 AM
Apr-27-2017, 09:54 AM
I have created 2 different .txt files in the directory of the script called
and i have written
What I did was to create a list called
after that by using endswith method
and then last part was to read each file and see if it was containing the word
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_:
Apr-27-2017, 10:27 AM
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.
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.