How to use to find files recursively?

There are a couple of ways: pathlib.Path().rglob() Use pathlib.Path().rglob() from the pathlib module, which was introduced in Python 3.5. from pathlib import Path for path in Path(‘src’).rglob(‘*.c’): print(path.name) glob.glob() If you don’t want to use pathlib, use glob.glob(): from glob import glob for filename in glob(‘src/**/*.c’, recursive=True): print(filename) For cases where matching files beginning with … Read more

How to count the number of files in a directory using Python

os.listdir() will be slightly more efficient than using glob.glob. To test if a filename is an ordinary file (and not a directory or other entity), use os.path.isfile(): import os, os.path # simple version for working with CWD print len([name for name in os.listdir(‘.’) if os.path.isfile(name)]) # path joining version for other paths DIR = ‘/tmp’ … Read more

How can I search sub-folders using glob.glob module? [duplicate]

In Python 3.5 and newer use the new recursive **/ functionality: configfiles = glob.glob(‘C:/Users/sam/Desktop/file1/**/*.txt’, recursive=True) When recursive is set, ** followed by a path separator matches 0 or more subdirectories. In earlier Python versions, glob.glob() cannot list files in subdirectories recursively. In that case I’d use os.walk() combined with fnmatch.filter() instead: import os import fnmatch … Read more

How to use glob() to find files recursively?

pathlib.Path.rglob Use pathlib.Path.rglob from the the pathlib module, which was introduced in Python 3.5. from pathlib import Path for path in Path(‘src’).rglob(‘*.c’): print(path.name) If you don’t want to use pathlib, use can use glob.glob(‘**/*.c’), but don’t forget to pass in the recursive keyword parameter and it will use inordinate amount of time on large directories. … Read more

tech