Directory.GetFiles("path/to/dir", "*.*", SearchOption.AllDirectories) but in Python

Question:

There’s Directory.GetFiles("path/to/dir", "*.*", SearchOption.AllDirectories) in C#,but is there same or similar function to search files in all directories?

Asked By: Natan

||

Answers:

You can use os.walk('path/to/dir')

From the documentation

Generate the file names in a directory tree by walking the tree either
top-down or bottom-up. For each directory in the tree rooted at
directory top (including top itself), it yields a 3-tuple (dirpath,
dirnames, filenames).

dirpath is a string, the path to the directory. dirnames is a list of
the names of the subdirectories in dirpath (excluding ‘.’ and ‘..’).
filenames is a list of the names of the non-directory files in
dirpath. Note that the names in the lists contain no path components.
To get a full path (which begins with top) to a file or directory in
dirpath, do os.path.join(dirpath, name).

For matching filenames you can use fnmatch

Answered By: kinshukdua

There’s xxx in C#, is there a similar function to search files in all directories in Python?

Take look at glob.glob with recursive=True, example usage let say you are structure like

dir1
 dir2
  dir3
   file.txt

then

import glob
for filename in glob.glob("**/*.txt",recursive=True):
    print(filename)

output

dir1/dir2/dir3/file.txt
Answered By: Daweo
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.