Created
May 22, 2020 07:52
-
-
Save SamyBencherif/f28d6ed66b48873cf5ac8bb826ab3536 to your computer and use it in GitHub Desktop.
Intuitive file search written in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import os | |
def usage(): | |
print("""python ifsearch.py --list <path> | |
python ifsearch.py --dump <path> | |
python ifsearch.py --search <term> <path>""") | |
indention = 0 | |
def indent(): | |
global indention | |
indention += 1 | |
def dedent(): | |
global indention | |
indention -= 1 | |
def iprint(s): | |
print(' |' * indention + s) | |
def listing(p): | |
for F in sorted(os.listdir(p)): | |
if os.path.isdir(p + os.sep + F): | |
iprint(F + ":") | |
indent() | |
listing(p + os.sep + F) | |
dedent() | |
else: | |
iprint(F) | |
def dump(p): | |
for F in sorted(os.listdir(p)): | |
if os.path.isdir(p + os.sep + F): | |
iprint(F + ":") | |
indent() | |
dump(p + os.sep + F) | |
dedent() | |
else: | |
iprint(F) | |
indent() | |
file_contents = open(p + os.sep + F, 'rt').read().split("\n") | |
longest_line = max([len(ln) for ln in file_contents])+5 | |
iprint("_"*(longest_line-2)) | |
c = 1 | |
for ln in file_contents: | |
iprint(f'{c} {ln}'.ljust(longest_line-2) + ' |') | |
c += 1 | |
iprint("`"*(longest_line-2)) | |
dedent() | |
def qmatch(term, sample): | |
sample = sample.lower() | |
sample = sample.strip() | |
return term in sample | |
def search(term, p): | |
for F in sorted(os.listdir(p)): | |
if os.path.isdir(p + os.sep + F): | |
if qmatch(term, F): | |
iprint(p + os.sep + F + ":") | |
indent() | |
search(term, p + os.sep + F) | |
dedent() | |
else: | |
if qmatch(term, F): | |
iprint(p + os.sep + F) | |
indent() | |
file_contents = open(p + os.sep + F, 'rt').read().split("\n") | |
longest_line = max([len(ln) for ln in file_contents])+5 | |
first_match = True | |
c = 1 | |
for ln in file_contents: | |
if qmatch(term, ln): | |
if first_match: | |
iprint(p + os.sep + F) | |
indent() | |
iprint("_"*(longest_line-2)) | |
iprint(f'{c} {ln}'.ljust(longest_line-2) + ' |') | |
first_match = False | |
c += 1 | |
if not first_match: | |
iprint("`"*(longest_line-2)) | |
dedent() | |
dedent() | |
if __name__ == "__main__": | |
if len(sys.argv) == 1: | |
usage() | |
elif len(sys.argv) == 3: | |
if sys.argv[1] == "--list": | |
listing(sys.argv[2]) | |
elif sys.argv[1] == "--dump": | |
dump(sys.argv[2]) | |
elif len(sys.argv) == 4 and sys.argv[1] == "--search": | |
search(sys.argv[2], sys.argv[3]) | |
else: | |
usage() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment