Newbie here! I am trying to make a simple python program that when called from the command line, would search all the .txt files in a given directory for a given string inside the files by typing something like this
> python mygrep.py ":" "C:\"
Also, i want to specifically use the fileinput module.
I have several issues with the code below, the least of which is my txt file filter doesn't work 100% and i have no idea why. The other is a weird traceback error i get at the command prompt. PLEASE help.
import fileinput, sys, string, os
def main():
searchterm = sys.argv[1]
targetdir = os.listdir(sys.argv[2])
for item in targetdir:
if not('.txt' in item):
targetdir.remove(str(item))
print item, "removed"
else:
print item
print targetdir
for line in fileinput.input(targetdir):
num_matches = string.count(line, searchterm)
if num_matches: # a nonzero count means there was a match
print "found '%s' %d times in %s on line %d." % (searchterm, num_matches,
fileinput.filename(), fileinput.filelineno())
if __name__ == '__main__':
main()