From 5c1c3ff92f1376513a0a9df1f4b5dbde174eab52 Mon Sep 17 00:00:00 2001 From: Manzoor Ahamed Date: Sat, 3 Jul 2021 08:47:39 +0530 Subject: [PATCH 1/2] File search in a directory --- 02-file-search.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100755 02-file-search.py diff --git a/02-file-search.py b/02-file-search.py new file mode 100755 index 0000000..38be036 --- /dev/null +++ b/02-file-search.py @@ -0,0 +1,29 @@ +#!/opt/anaconda3/bin/python3 + +## Modules +import pathlib +import argparse + +## Create the parser +parser = argparse.ArgumentParser() + +## Add the arguments +parser.add_argument("arg1", help="Directory Name") +parser.add_argument("arg2", help="File Name to search for in the dir") + +## Execute the parse_arg() method +args = parser.parse_args() + + + +dir = pathlib.Path(args.arg1) +file = pathlib.Path(args.arg1,args.arg2) + +if dir.is_dir(): + print("Directory exists") + if file.is_file(): + print("The file %s exist in the %s directory" %(args.arg2,args.arg1)) + else: + print("The dir %s exist but the file %s is not in the directory" %(args.arg1,args.arg2)) +else: + print("The directory %s doesnt exist" %args.arg1) From 11e8634a6d4e64599da32a29049be599cfecc1e1 Mon Sep 17 00:00:00 2001 From: Manzoor Ahamed Date: Sat, 3 Jul 2021 12:34:57 +0530 Subject: [PATCH 2/2] Added try/except and implemented the logic into the function --- 02-file-search.py | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/02-file-search.py b/02-file-search.py index 38be036..b7757bb 100755 --- a/02-file-search.py +++ b/02-file-search.py @@ -4,6 +4,21 @@ import pathlib import argparse +## Function +def file_search(dir,file): + try: + if dir.is_dir(): + #print("Directory exists") + if file.is_file(): + print("The file %s exist in the %s directory" %(args.arg2,args.arg1)) + else: + print("The dir %s exist but the file %s is not in the directory" %(args.arg1,args.arg2)) + else: + print("The directory %s doesnt exist" %args.arg1) + except: + print("Something went wrong") + + ## Create the parser parser = argparse.ArgumentParser() @@ -14,16 +29,7 @@ ## Execute the parse_arg() method args = parser.parse_args() - - dir = pathlib.Path(args.arg1) file = pathlib.Path(args.arg1,args.arg2) -if dir.is_dir(): - print("Directory exists") - if file.is_file(): - print("The file %s exist in the %s directory" %(args.arg2,args.arg1)) - else: - print("The dir %s exist but the file %s is not in the directory" %(args.arg1,args.arg2)) -else: - print("The directory %s doesnt exist" %args.arg1) +file_search(dir,file)