-
Notifications
You must be signed in to change notification settings - Fork 0
/
find.py
47 lines (38 loc) · 1.31 KB
/
find.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import os, fnmatch, sys, getopt
dir_to_search = ''
search_pattern = ''
def showerror():
print('\tCorrect usage is:')
print ('\tfind.py -d <dir_to_search> -p <pattern_to_search>')
sys.exit(2)
try:
## Parsing option and argument variable
opts, args = getopt.getopt(sys.argv[1:],"hd:p:",["dir=","pattern="])
# print(opts, args)
except getopt.GetoptError:
showerror()
for opt, arg in opts:
if opt == '-h':
print ('find.py -d <dir_to_search> -p <pattern_to_search>')
sys.exit()
elif opt in ("-d", "--dir"):
dir_to_search = arg
elif opt in ("-p", "--pattern"):
search_pattern = arg
## Check directory path exist or not if not then assign it current directory
if len(dir_to_search) == 0:
dir_to_search = os.getcwd()
## Check search pattern has any value or not if not then throw error
if len(search_pattern) == 0:
showerror()
print(dir_to_search, search_pattern)
# Walk through directory
exclude_prefixes = ['$RECYCLE.BIN', '$Recycle.Bin', '$PatchCache$'] # You can add other folder name which you want to exclude in search
for dirpath, dirnames, filenames in os.walk(dir_to_search):
for exclude in exclude_prefixes:
if exclude in dirpath:
break;
else:
for fileName in filenames:
if fnmatch.fnmatch(fileName, search_pattern): # Match search string
print(os.path.join(dirpath, fileName))