Suppose there is a directory DIR1 form C:\\Users\\Admin . There is also a list that looks something like this: ['f1', 'f2', 'f3', 'f4', 'f5'] , and the file name: FILE1 . The list represents possible folder names at DIR1 .

What is the fastest way to find all files with the name FILE1 , if it can be located only along the path DIR1\<f1-f5> , one or two levels deeper? That is, possible addresses can be approximately like this: DIR1\f2\FILE1 DIR1\f4\any_folder\FILE1 , DIR1\f4\any_folder\FILE1 DIR1\f4\qwe\asd\FILE1 , DIR1\f4\qwe\asd\FILE1 .

I tried to experiment with os.walk , glob , pathlib , etc., but it’s not very pathlib to determine for myself, and I hardly ever used all possible methods ...

    1 answer 1

     #!/usr/bin/env python3 #-*- coding: utf-8 -*- # писал под linux, под windows может чтото пойти не так, точно не знаю. import os dir_name="/home/user1/development/stackoverflow/DIR1" # Задаем путь к папке где будет поиск файла dir_map=os.walk(dir_name) # Создаем объект генератор, который при переборе возвращающий кортежы для всех вложенных папок где, нулевой элемент кортежа это адрес папки, первый элемент это список вложенных папок, а второй элемент список вложенных файлов. for i in dir_map: # перебираем генератор if "FILE1" in i[2]: print(i[0]+"/FILE1") # Если в списке файлов есть "FILE1" , выводим на экран.