-2

I am using an os.walk() loop and if statement to find the path of a file. It works, however after the path is found and printed the loop doesn't break for a few seconds after this. I want to break the loop after the path I want is printed. New to recursion so this is where I am falling short.

Code:

for root, dirs, files in os.walk('C:\\'):
  for file in files:
     if file == 'vipkidt.exe':
          path = str(os.path.join(root, file))
          print(path)

Output>> C:\Program Files (x86)\VIPKIDT\vipkidt.exe
         # 3-4 seconds passes..
         Process finished with exit code 0

Wanted path is printed fairly qucikly, 3-4 seconds passes, then loop breaks. I want these 3-4 seconds shaved off. I have tried adding a break at each the inner and outer for loop, however didn't do the trick. I referenced these posts here but still wasn't clicking: ref1, ref2

Los
  • 67
  • 5
  • 1
    'break' keyword – Russ J Dec 03 '20 at 20:02
  • [break](https://docs.python.org/3/reference/simple_stmts.html#break) – Maurice Meyer Dec 03 '20 at 20:02
  • Stack Overflow is not intended to replace existing documentation and tutorials. Loop control is included in any tutorial on the topic. We expect you to do that research before posting here. Please repeat [on topic](https://stackoverflow.com/help/on-topic) and [how to ask](https://stackoverflow.com/help/how-to-ask) from the [intro tour](https://stackoverflow.com/tour). – Prune Dec 03 '20 at 20:17
  • 1
    I know I need a `break` keyword, I already tried that before posting the question, the missing piece was the empty `dirs` as @Justin mentioned below. – Los Dec 05 '20 at 10:35

1 Answers1

1

Use break to get out of the for file in files loop and empty dirs to get out of the os.walk loop

for root, dirs, files in os.walk('C:\\'):
    for file in files:
        if file == 'vipkidt.exe':
            path = str(os.path.join(root, file))
            print(path)
            dirs[:] = []
            break