I have the code to evaluate all the files in a directory and list the files containing the specified string.
What I need to do is to have this loop over multiple sub-directories.
I've tried using os.walk but without success.
Appreciate any assistance. This is my original query:
import os
path = input('Directory Path: ')
directory = os.listdir(path)
searchstring1 = input('Search String: ')
for fname in directory:
if os.path.isfile(path + os.sep + fname):
f = open(path + os.sep + fname, 'r')
if searchstring1 in f.read():
print('found string in file %s' % fname)
f.close()
This is what I thought would work:
import os
path = input('Directory Path: ')
searchstring1 = input('Search String: ')
for root, dirs,files in os.walk(path):
for fname in files:
f = open(fname, 'r')
if searchstring1 in f.read():
print('found string in file %s' % fname)
f.close()
What's being missed here?