Pregunta

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??

¿Fue útil?

Solución

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:
             ...
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top