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:
...
Question
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??
Solution
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:
...