Улучшите функцию поиска файлов, чтобы также находить папкиPython

Программы на Python
Ответить
Anonymous
 Улучшите функцию поиска файлов, чтобы также находить папки

Сообщение Anonymous »

В настоящее время у меня есть следующая функция, которая «находит» указанный файл (по имени файла) в каталоге проекта (возвращает полный путь к файлу). Я использую для работы с файлом без необходимости вручную указывать полный путь к файлу.
Что я хотел бы сделать, так это обобщить его, чтобы он также мог «найти» указанную папку. Однако после некоторых поисков я не уверен, каким будет лучший способ реализовать это. Я полагаю, что дополнительным улучшением было бы каким-то образом обрабатывать случаи, когда несколько файлов или папок в каталоге проекта имеют одно и то же имя (в настоящее время я избегаю файлов с одинаковыми именами, но с моей структурой папок это может быть проблемой с папками). Я думаю, что есть несколько способов внести эти улучшения, но мне хотелось бы узнать мнение о том, каким может быть идеальный способ сделать это.
import os
import difflib
def file_checker(file_name, file_type):
"""
As opposed to file_checker(), this function searches through the full BPL Lab directory structure to try and find
the specified file.
Args:
file_name: str, full file path of the desired file.
OR
name of the file without file extension, if the file is in the project directory.
file_type: str, the type of file to be searched, can include the '.' so '.csv' or 'csv' are both valid.
OR
A list of file types to be searched.

Returns:
The full file path of the desired file, if it exists. If the file cannot be found then an error will be raised
with suggestions if a similar file name is found.

"""
scrip_dir = os.path.abspath(__file__) # gets the BPL_code.py path
proj_dir = scrip_dir.replace(r'\Event-Camera-Code\BPL_utils.py','') #gets top level folder of the project

# Check if the file_name is already the full file path
if os.path.isfile(file_name):
print(f"Looking at file '{file_name}'.")
return file_name #already done
# If file_name is not a complete file path already
try:
all_files = []
for root, dirs, files in os.walk(proj_dir): #gets all files in the project directory
for file in files:
all_files.append(os.path.join(root, file))
except FileNotFoundError:
raise FileNotFoundError(f"The directory {proj_dir} does not exist.") #Should be impossible to happen but idk
# Filter only files of the same type
if type(file_type)==str:
same_type_files = [file for file in all_files if file_type in str(file)]
if type(file_type)==list:
same_type_files = [file for file in all_files if any(ext in str(file) for ext in file_type)]
file_found=False
for file in same_type_files:
curr_file_1=os.path.basename(file)
curr_file_name, curr_file_extension = os.path.splitext(curr_file_1)
if file_name==curr_file_name and 'tmp' not in curr_file_extension:
file_found=True
print(f"Looking at file '{file}'.")
return file

if file_found==False: #if no exact matches have been found look for suggestions.
# Find the closest match using difflib
same_type_files_base=[os.path.basename(file) for file in same_type_files]
closest_matches = difflib.get_close_matches(file_name, same_type_files_base, n=1, cutoff=0.6)
# Raise FileNotFoundError with suggestion if a close match is found
if closest_matches:
suggestion = closest_matches[0]
suggestion_name, suggestion_extension = os.path.splitext(suggestion)
raise FileNotFoundError(
f"The file '{file_name}' with file type {file_type} does not exist. Did you mean '{suggestion_name}' with file type '{suggestion_extension}'?"
)
else:
# If no close matches are found, raise error without suggestion
raise FileNotFoundError(f"The file '{file_name}' does not exist and no similar files were found.")


Подробнее здесь: https://stackoverflow.com/questions/798 ... lders-also
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»