0

Hi i wrote this code for searching a keyword in a list of files

import glob
import os
print "enter directory path"
path=raw_input()
print "Enter keyword"
key=raw_input()
os.chdir(path)
for files in glob.glob("*.*"):
    with open(file) as f:
         contents=f.read()
    if key in contents:
          print file

I am relatively new to Python.Can anyone please help me to modify the same for searching in sub directory too??

amaluth
  • 87
  • 3
  • 11

1 Answers1

0

Use os.walk:

for root, dirs, files in os.walk(your_dir_path):
    for file in files:
        file = os.path.join(root, file)    
        with open(file) as f:
             ...
warvariuc
  • 57,116
  • 41
  • 173
  • 227
  • I tried this one but it shows an error like this Traceback (most recent call last): File "s.py", line 10, in with open(file) as fdf: IOError: [Errno 2] No such file or directory: 'accounts.cfg' – amaluth Feb 10 '14 at 07:54
  • if you are using linux, it's much faster to call `grep` using `subprocess` module – warvariuc Feb 10 '14 at 08:37
  • I dont know how to use that.I'm just a beginner – amaluth Feb 10 '14 at 09:15