There's Directory.GetFiles("path/to/dir", "*.*", SearchOption.AllDirectories)
in C#,but is there same or similar function to search files in all directories?
CodePudding user response:
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
CodePudding user response:
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