You can set the recursive keyword argument in the glob.glob() method to True for the program to search recursively through the files of the folders, subfolders, etc.
from glob import glob
path = 'C:\\Users\\User\\Desktop'
for file in glob(path + '\\**\\*.txt', recursive=True):
with open(file) as f:
text = f.read()
if '20210624' in text and '20210625' not in text:
print(file)
If you don't want to entire path of the files to be printed; only the filenames, then:
from glob import glob
path = 'C:\\Users\\User\\Desktop'
for file in glob(path + '\\**\\*.txt', recursive=True):
with open(file) as f:
text = f.read()
if '20210624' in text and '20210625' not in text:
print(file.split('\\')[-1])
In order to use the os.walk() method, you can use the str.endswith() method (as you have done in your post) like so:
import os
for path, _, files in os.walk('C:\\Users\\User\\Desktop'):
for file in files:
if file.endswith('.txt'):
with open(os.path.join(path, file)) as f:
text = f.read()
if '20210624' in text and '20210625' not in text:
print(file)
And to search within a maximum level of subdirectories:
import os
levels = 2
root = 'C:\\Users\\User\\Desktop'
total = root.count('\\') + levels
for path, _, files in os.walk(root):
if path.count('\\') > total:
break
for file in files:
if file.endswith('.txt'):
print(os.path.join(path, file))