import sys, getopt, os, fnmatch
from glob import glob
inputdir = "..\..\.."
outputfile = "results"
def main(argv):
try:
opts, args = getopt.getopt(argv, "hd:t:", ["dfile=", "text="])
except getopt.GetoptError:
print("go.py -d
-t ")
sys.exit(2)
for opt, arg in opts:
if opt == "-h":
print("go.py -d -t ")
sys.exit()
elif opt in ("-d", "--directory"):
dir = arg
dir = "./*.c"
print(f"dir = {dir}")
elif opt in ("-t", "--text"):
text_to_search_for = arg
text_to_search_for = "blah"
print(f"text_to_search_for = {text_to_search_for}")
all_files = open("./all_files.txt", "w")
found_files = open("./found_files.txt", "w")
text_to_search_for = "blah"
dir = "*/*.c"
def find_files(directory, pattern):
for root, dirs, files in os.walk(directory):
for basename in files:
if fnmatch.fnmatch(basename, pattern):
filename = os.path.join(root, basename)
yield filename
for index, filename in enumerate(find_files('.', '*.c')):
try:
print(f"{index} {filename}")
all_files.write(f"file number = {index}\t\tfile name = {filename}\n")
with open(filename, "r") as f:
file_contents = f.read()
#print(f"text_to_search_for = {text_to_search_for}")
#print("file_contents.find(text_to_search_for) = ",file_contents.find(text_to_search_for))
#print("int(file_contents.find(text_to_search_for)) = ",int(file_contents.find(text_to_search_for)))
location = file_contents.find(text_to_search_for)
#print(f"location = {location}")
if location > -1:
#print(f"File number = {index}")
#print(f"Found {text_to_search_for}")
found_files.write(f"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n")
found_files.write(f"Searching for {text_to_search_for}\n")
found_files.write(f"File number = {index}\n")
found_files.write(f"{filename}\n")
found_files.write(f"At location {location}\n")
found_files.write(f"{file_contents[location-100:location+100]}\n\n")
except UnicodeDecodeError:
pass
if __name__ == "__main__":
main(sys.argv[1:])
found_files.close()
all_files.close()