Reputation: 3806
I'm trying to search for a string in all text and log files in the current directory. And if it finds a match, print the text or log file where the match was found. Is this possible, and how can I manipulate the code below to accomplish this task?
fiLe = open(logfile, "r")
userString = raw_input("Enter a string name to search: ")
for line in fiLe.readlines():
if userString in line:
print line
Upvotes: 7
Views: 21854
Reputation: 2728
He asked for a flat readdir, not for a recursive file tree walk. os.listdir() does the job.
Upvotes: 3
Reputation: 342869
Something like this:
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()
Upvotes: 18
Reputation: 72815
Do you have to do it in Python? Otherwise, simply grep -l "string" *.txt *.log
would work.
Upvotes: 2