需要一个python脚本来搜索sql文件集合中的特定关键字,并返回找到每个关键字的索引
我对python非常陌生,我只是想知道如何获取文件集合(sql),并使用一些特定的关键字,找到它们在所有文件中匹配的代码行。任何观念、想法或建议都会对拯救生命大有裨益 问候 蒂亚戈M解决方案需要一个python脚本来搜索sql文件集合中的特定关键字,并返回找到每个关键字的索引,python,sql,search,Python,Sql,Search,我对python非常陌生,我只是想知道如何获取文件集合(sql),并使用一些特定的关键字,找到它们在所有文件中匹配的代码行。任何观念、想法或建议都会对拯救生命大有裨益 问候 蒂亚戈M解决方案 s = 'somestring' names = ['file1.sql', 'file2.sql'] for n in names: f = open(n) lines = f.readlines() for i, l in enumerate(lines):
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)
您需要查看
os.walk
功能,然后打开每个文件,并在中使用,字符串。查找,或在每个文件的行上重新搜索。例如:
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)
它必须是Python吗?你能改为grep-n
搜索关键词吗?我会试试看,然后告诉你!谢谢你!谢谢你!!非常感谢!