Need a python script to search specific keywords in a collection of sql files returning the index of where each keyword was found
I'm extremely new to python and I was just wondering how could I take a collection of files (sql), and using some specific keywords, find which line of code they are matched throughout all the files. Any notions, ideas or suggestions would be li开发者_开发技巧fe savingly helpful.
Kind Regards
Tiago M
Solution
s = 'somestring'
names = ['file1.sql', 'file2.sql']
for n in names:
f = open(n)
lines = f.readlines()
for i, l in enumerate(lines):
if s in l:
print 'line %d' % (i)
You want to look at the os.walk
function then open
each file and use in
, string.find
, or re.search
on the lines of each file. For example:
search_term = "where x > 1"
for directory, subdirectories, paths in os.walk("/path/to/sql_directory"):
for path in paths:
f = open(path, "r")
for line_no, line in enumerate(f):
if search_term in line: # could use re module functions here
print "%s(%d): %s"%(path, line_no, line)
精彩评论