我已经看过几个如何显示行数的例子,并尝试在我的代码中实现这些,但是没有成功。我是一个Python新手,所以我想我还有更多需要学习的东西。有人可以告诉我如何显示文件中找到的匹配的行数,谢谢?
elif searchType =='3':
print "Directory to be searched: c:\SQA_log "
print " "
directory = os.path.join("c:\\","SQA_log")
regex = re.compile(r'(?:3\d){6}')
for root,dirname, files in os.walk(directory):
for file in files:
if file.endswith(".log") or file.endswith(".txt"):
f=open(os.path.join(root,file))
for line in f.readlines():
searchedstr = regex.findall(line)
for word in searchedstr:
print "String found: " + word
print "File: " + os.path.join(root,file)
break
f.close()
答案 0 :(得分:3)
好吧,我假设你也想输出行号。为此,你会这样做:
regex = re.compile(r'(?:3\d){6}')
for root,dirname, files in os.walk(directory):
for file in files:
if file.endswith(".log") or file.endswith(".txt"):
f=open(os.path.join(root,file))
for i, line in enumerate(f.readlines()):
searchedstr = regex.findall(line)
for word in searchedstr:
print "String found: " + word
print "Line: "+str(i)
print "File: " + os.path.join(root,file)
break
f.close()
答案 1 :(得分:2)
见http://docs.python.org/library/functions.html#enumerate。使用迭代线更改循环,如下所示:
for i,line in enumerate(f.readlines()):
我将保留行号