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

有帮助吗?

解决方案

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:
             ...
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top