0

Find a given file recursively inside a dir. The code I tried is not showing any output, though I have a file C:\Users\anaveed\test\hoax\a.txt

Below the code

import glob
import os

os.chdir(r'C:\Users\anaveed\test')
for f in glob.iglob('a.txt', recursive=True):
    print(f)

No output

Nav
  • 143
  • 9
  • Possible duplicate of [How do I list all files of a directory?](https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory) – KarateKid Jul 01 '19 at 12:54

2 Answers2

1

Looks like you need.

import glob

for f in glob.iglob(r'C:\Users\anaveed\test\**\a.txt', recursive=True):
    print(f)
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0

This is another way of doing it:

import os

path = r'C:\Users\anaveed\test'
filename = 'a.txt'
for root, dirs, files in os.walk(path):
    for name in files:
        if name == filename:
            print(os.path.join(root, name))

A couple of comments:

  1. you do not need to use glob if you are not specifying wildcards, just use os.walk()
  2. you do not need to move to a specific path to look for files therein, just save the path into a variable.
  3. it would be even better to wrap this into a function (perhaps using a list comprehension).
  4. the glob solution is typically faster.
norok2
  • 25,683
  • 4
  • 73
  • 99