0

I've been trying to figure out how I can loop through a root directory with sub directories and search for a file. If a specific file exists then run a script.

File structure example: Root --Folder 1 ----TEST.txt --Folder 2 ----[no files] --Folder 3 ----TEST.txt

What I am trying to achieve is having the .py file in Root. When run it will loop over each folder in Root, if the file TEST.txt then do some processing.

Notes: There will always be folders in Root Where processing is needed there will be a file called TEST.txt There will definitely be some folders that do not have TEST.txt

Pseudo code: From Root open Folder 1. If TEST.txt is there then do some cool stuff and then 'cd ../' and repeat process but look in Folder 2. Stop looping when all Folders have been checked.

2
  • 2
    Check out os.walk and os.listdir : docs.python.org/3/library/os.html Commented Jun 15, 2018 at 18:02
  • Thanks for that, I never knew about those. Will do more research on them. Commented Jun 15, 2018 at 19:24

1 Answer 1

2

This code should be able to search all folders and sub folders for a file.

import os

thisdir = os.getcwd()
for root, dirs, files in os.walk(thisdir):
    if 'TEST.txt' in files:
        #do some processing

Joining 'root' and the file name should be able to give you access to that file if you want to execute or analyze it somehow.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, (quickly tested in a VM) exactly what I needed. Thanks so much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.