I’m trying to find a string in files contained within a directory. I have a string like banana
that I know that exists in a few of the files.
import os import sys user_input = input("What is the name of you directory?") directory = os.listdir(user_input) searchString = input("What word are you trying to find?") for fname in directory: # change directory as needed if searchString in fname: f = open(fname,'r') print('found string in file %s') %fname else: print('string not found')
When the program runs, it just outputs string not found
for every file. There are three files that contain the word banana
, so the program isn’t working as it should. Why isn’t it finding the string in the files?
Advertisement
Answer
You are trying to search for string
in filename
, use open(filename, 'r').read()
:
import os user_input = input('What is the name of your directory') directory = os.listdir(user_input) searchstring = input('What word are you trying to find?') for fname in directory: if os.path.isfile(user_input + os.sep + fname): # Full path f = open(user_input + os.sep + fname, 'r') if searchstring in f.read(): print('found string in file %s' % fname) else: print('string not found') f.close()
We use user_input + os.sep + fname
to get full path.
os.listdir
gives files and directories names, so we use os.path.isfile
to check for files.