import os
# 定义要查找的特定字符串
specific_strings = ["vvv", "fff", "eee"]
# 遍历文件夹及子文件夹中的所有txt文件
results = []
for root, dirs, files in os.walk("."):
for dir in dirs:
dir_path = os.path.join(root, dir)
for filename in os.listdir(dir_path):
if filename.endswith(".txt"):
filepath = os.path.join(dir_path, filename)
with open(filepath, "r") as file:
lines = file.readlines()
# 查找特定字符串所在的行的全部内容
matches = [f"{specific_string}: {line.strip()}" for line in lines for specific_string in specific_strings if specific_string in line]
if matches:
# 将结果存储到列表中
result = f"{filename}: {', '.join(matches)}"
results.append(result)
# 将结果保存到一个新的txt文件中
with open("output.txt", "w") as file:
file.write("\n".join(results))
一个文件夹下面有二十个子文件夹,每个子文件夹下面还有一个子文件夹,其中有若干txt文件,使用python识别到这些txt文件的3个特定字符串,分别为:vvv,fff,eee。返回结果是文件名+特定字符串所在行的全部内容,将返回结果保存到一个新的txt文件中