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
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()
He asked for a flat readdir, not for a recursive file tree walk. os.listdir() does the job.
Do you have to do it in Python? Otherwise, simply grep -l "string" *.txt *.log
would work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With