如何检查文件内的所有文件夹和文件内的子文件夹是否存在特定字符串
- 我有文件夹和文件
- 我也有子文件夹和文件
- 我需要搜索同一文件中也存在的特定字符串,其他字符串不存在
- 所有文件都在
.txt - 我需要检查文件中哪些字符串
20210624存在于文件中,哪些字符串20210625不在文件中 - 我的输出返回文件名
import os
match_str = ['20210624']
not_match_str = ['20210625']
for root, dirs, files in os.walk(path):
for name in files:
if name.endswith((".txt")):
## search files with match_str `20210624` and not_match_str `20210625`
我可以使用 import walk
回答
您可以recursive在glob.glob()方法中设置关键字参数,True以便程序递归搜索文件夹、子文件夹等文件。
from glob import glob
path = 'C:UsersUserDesktop'
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:UsersUserDesktop'
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:UsersUserDesktop'):
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:UsersUserDesktop'
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))