你可以在
glob.glob()
方法中设置
recursive
关键字参数为
True
,让程序递归搜索文件夹、子文件夹等。
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)
如果您不想打印文件的完整路径,只需要文件名,则可以执行以下操作:
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])
为了使用
os.walk()
方法,你可以像这样使用
str.endswith()
方法
(就像你在帖子中所做的那样):
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)
并且在最大子目录级别内进行搜索:
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))