Files
link-fixer/search_file.py
2024-08-16 00:27:16 -04:00

49 lines
1.3 KiB
Python

# search_file.py
# searching for target file in a given dir
# prompt user if multiple are found
import os
import errno
from fnmatch import fnmatch
import warnings
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):
match_path = os.path.join(root, name)
if not os.path.islink(match_path):
results.append(match_path)
return results
def print_num_list(paths):
n = 1
for p in paths:
print(f"{n}. {p}")
n += 1
return 0
def select_path(filename, 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(f"Multiple matches found for {filename}")
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 :
raise Exception(f"No match found for {filename}")
p = select_path(filename, paths)
return p