search_file break up and test -- not working yet
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
# search_file.py
|
||||
# searching for target file in a given dir
|
||||
# prompt user if multiple are found
|
||||
|
||||
import os
|
||||
from fnmatch import fnmatch
|
||||
|
||||
def search_all_match(filename, path):
|
||||
# search part shamelessly copied from stack overflow...
|
||||
# real author: Nadia Alramli
|
||||
results = []
|
||||
for root, dirs, files in os.walk(path):
|
||||
for name in files:
|
||||
if fnmatch(filename, name):
|
||||
results.append(os.path.join(root, name))
|
||||
return results
|
||||
|
||||
def print_num_list(paths):
|
||||
n = 1
|
||||
for p in paths:
|
||||
print(f"{n}. {p}")
|
||||
n += 1
|
||||
return 0
|
||||
|
||||
def select_path(paths):
|
||||
l = len(paths)
|
||||
if l == 0 :
|
||||
raise Exception("Error select_path - empty list")
|
||||
elif l == 1 :
|
||||
return paths[0]
|
||||
c = '0'
|
||||
while not (c.isdigit() and 0 < int(c) <= l):
|
||||
print("Multiple matches found.")
|
||||
print("Please select target:")
|
||||
print_num_list(paths)
|
||||
c = input(f"Please select file to link to: (1-{l})")
|
||||
return paths[int(c)-1]
|
||||
|
||||
def search_file(filename, path):
|
||||
paths = search_all_match(filename, path)
|
||||
if len(paths) == 0 :
|
||||
print(f"No match for \"{filename}\". Link not modified.")
|
||||
raise Exception(FileNotFoundError)
|
||||
p = select_path(paths)
|
||||
return p
|
||||
|
||||
Reference in New Issue
Block a user