0

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?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Jim Herbert
  • 29
  • 2
  • 5
  • 1
    Show us how you were trying to use `os.walk()` please. Why didn't that work? – Martijn Pieters May 16 '18 at 15:45
  • I've tried several iterations but here is what I thought was most promising: path = input('Directory Path: ') directory = os.listdir(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() – Jim Herbert May 16 '18 at 16:00
  • Please [edit] your question to add that. You don't need to also use `os.listdir()` when using `os.walk()`. – Martijn Pieters May 16 '18 at 16:02
  • The `files` list consists of *just* the names in the given directory, so you'd want to use `os.path.join(root, fname)` when opening. – Martijn Pieters May 16 '18 at 16:03
  • s.path.join(root, fname) worked. – Jim Herbert May 16 '18 at 16:12

0 Answers0