Directory.GetFiles("path/to/dir", "*.*", SearchOption.AllDirectories) 但在 Python

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

C#中有Directory.GetFiles("path/to/dir", "*.*", SearchOption.AllDirectories),但是否有相同或相似的功能可以在所有目录中搜索文件?

您可以使用os.walk('path/to/dir')

来自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).

要匹配文件名,您可以使用 fnmatch

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

看看 glob.globrecursive=True,示例用法假设您的结构类似于

dir1
 dir2
  dir3
   file.txt

然后

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

产出

dir1/dir2/dir3/file.txt