suf*_*ffa 7 python file-io search
我正在尝试在当前目录中的所有文本和日志文件中搜索字符串.如果找到匹配项,则打印找到匹配项的文本或日志文件.这是可能的,我如何操纵下面的代码来完成这项任务?
fiLe = open(logfile, "r")
userString = raw_input("Enter a string name to search: ")
for line in fiLe.readlines():
if userString in line:
print line
Run Code Online (Sandbox Code Playgroud)
gho*_*g74 18
像这样的东西:
import os
directory = os.path.join("c:\\","path")
for root,dirs,files in os.walk(directory):
for file in files:
if file.endswith(".log") or file.endswith(".txt"):
f=open(file, 'r')
for line in f:
if userstring in line:
print "file: " + os.path.join(root,file)
break
f.close()
Run Code Online (Sandbox Code Playgroud)