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 = []
for line in lines:
for specific_string in specific_strings:
if specific_string in line:
content = line.split(specific_string)[1].strip()
if content.isdigit():
matches.append(f"{specific_string}{content}")
if matches:
# 将结果存储到列表中
result = f"{os.path.basename(dir_path)}: {', '.join(matches)}"
results.append(result)
# 将结果保存到一个新的txt文件中
with open("output.txt", "w") as file:
file.write("\n".join(results))