Search nested folders with specific names in python

Sep 23, 2022
Reaction score
I am an employee of the hospital's medical records department, we scan patients' files and then store them in special folders, like below

Drive D --> scan folder ----> Name of the month ------> Acceptance number of the patient file (like 1015186) ------> Image of the patient's file as a JPEG file

The names of the photos are Document (1).jpeg, Document (2).jpeg, Document (3).jpeg and...

For a report, we need the first image of several patient files, which is called Document (1).jpeg.

We have the acceptance numbers in an excel file, that's why I want to write a code that goes into the scan folder and searches all its subfolders. When it finds a folder with the desired name, it goes into the folder and file document(1).jpeg Copy to another folder.

Currently, I have such a code, but this code is not correct

from openpyxl import load_workbook
import os
import shutil

wb = load_workbook('file.xlsx')
sr =
b = 35

for x in range(b):
    for root, dirs., files in os.walk("D:/Projects/python/scan"):
        for file in files:
            if file.endswith(str(sr.cell(x+1, 1).value) + ".jpeg"):
                shutil.copy(os.path.join(root, file), "D:/Projects/python/Hossein/" + file)
_Of course, I had written this code for another part, I wanted to change it a little to use it for this work, but unfortunately I couldn't._

In the end, I apologize that I am not fluent in English,
I wrote this text with the help of Google Translate.


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Latest member

Latest Threads