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?

5
  • 1
    Show us how you were trying to use os.walk() please. Why didn't that work? Commented May 16, 2018 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() Commented May 16, 2018 at 16:00
  • Please edit your question to add that. You don't need to also use os.listdir() when using os.walk(). Commented May 16, 2018 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. Commented May 16, 2018 at 16:03
  • s.path.join(root, fname) worked. Commented May 16, 2018 at 16:12

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.