任务背景
在根目录下会有很多文件夹,每个文件夹中都可能会有一个runlog的txt文件,我需要对根路径下1200个文件进行查询和记录,需要一个xlsx文件的记录,标题是文件夹名称和状态。
步骤
步骤:
1.遍历根路径下的所有文件夹(假设有1200个文件夹,我们不需要其他文件,只需要文件夹)。
2.对于每个文件夹,检查其中是否存在runlog.txt文件。
3.如果不存在,则记录该文件夹的状态为“失败”或“未运行”。
4.如果存在,则打开文件,读取内容,查找字符串"Status:”。
5.如果找到了"Status:“,则检查其后面的部分,直到遇到“|“为止,如果这个字符串是”Completed”,则标记为成功,否则为失败。
6.如果文件中没有"Status:”,则标记为失败。然后,我们将结果写入一个xlsx文件,包含两列:文件夹名称和状态。
代码
import os
import re
import pandas as pd
from pathlib import Path
def check_runlog_status(root_path, output_file="runlog_status.xlsx"):
"""
检查根路径下所有文件夹中的runlog文件状态
参数:
root_path: 根目录路径
output_file: 输出的Excel文件名
"""
# 存储结果的列表
results = []
# 遍历根路径下的所有项目
for item in Path(root_path).iterdir():
# 只处理文件夹
if item.is_dir():
folder_name = item.name
runlog_path = item / "runlog.txt"
# 检查runlog文件是否存在
if not runlog_path.exists():
status = "失败 - 文件不存在"
results.append([folder_name, status])
continue
try:
# 读取runlog文件内容
with open(runlog_path, 'r', encoding='utf-8') as file:
content = file.read()
# 使用正则表达式查找Status状态
status_match = re.search(r'Status:\s*(.*?)\|', content)
if status_match:
status_value = status_match.group(1).strip()
if status_value == "Completed":
status = "成功"
else:
status = f"失败 - 状态: {status_value}"
else:
status = "失败 - 未找到Status信息"
results.append([folder_name, status])
except Exception as e:
status = f"失败 - 读取错误: {str(e)}"
results.append([folder_name, status])
# 创建DataFrame并保存为Excel文件
df = pd.DataFrame(results, columns=["文件夹名称", "状态"])
df.to_excel(output_file, index=False)
print(f"检查完成!共处理 {len(results)} 个文件夹")
print(f"结果已保存到: {output_file}")
return df
def main():
# 设置根路径(请根据实际情况修改)
root_path = input("请输入根目录路径: ").strip()
# 验证路径是否存在
if not os.path.exists(root_path):
print("错误:指定的路径不存在!")
return
# 设置输出文件名
output_file = "runlog_status_report.xlsx"
# 执行检查
try:
result_df = check_runlog_status(root_path, output_file)
# 显示统计信息
success_count = len(result_df[result_df['状态'] == '成功'])
fail_count = len(result_df) - success_count
print(f"\n统计信息:")
print(f"成功: {success_count} 个")
print(f"失败: {fail_count} 个")
except Exception as e:
print(f"执行过程中发生错误: {str(e)}")
if __name__ == "__main__":
main()
更基础版本
import os
import pandas as pd
def simple_check_runlog_status(root_path):
"""
简化版的runlog状态检查
"""
results = []
# 遍历根目录下的所有文件夹
for folder_name in os.listdir(root_path):
folder_path = os.path.join(root_path, folder_name)
if os.path.isdir(folder_path):
runlog_path = os.path.join(folder_path, "runlog.txt")
# 检查文件是否存在
if not os.path.exists(runlog_path):
results.append([folder_name, "失败 - 文件不存在"])
continue
try:
# 读取文件内容
with open(runlog_path, 'r', encoding='utf-8') as file:
content = file.read()
# 查找Status信息
if "Status:Completed|" in content:
results.append([folder_name, "成功"])
else:
results.append([folder_name, "失败 - 状态不符"])
except Exception as e:
results.append([folder_name, f"失败 - 读取错误: {str(e)}"])
# 保存结果
df = pd.DataFrame(results, columns=["文件夹名称", "状态"])
df.to_excel("runlog_status.xlsx", index=False)
print(f"处理完成!共检查 {len(results)} 个文件夹")
return df
# 使用示例
if __name__ == "__main__":
root_path = "." # 当前目录,可以修改为你的根路径
simple_check_runlog_status(root_path)
import os
import pandas as pd
def simple_check_runlog_status(root_path):
"""
Simplified runlog status checker
"""
results = []
# Iterate through all folders in root directory
for folder_name in os.listdir(root_path):
folder_path = os.path.join(root_path, folder_name)
if os.path.isdir(folder_path):
runlog_path = os.path.join(folder_path, "runlog.txt")
# Check if file exists
if not os.path.exists(runlog_path):
results.append([folder_name, "Failed - File not found"])
continue
try:
# Read file content
with open(runlog_path, 'r', encoding='utf-8') as file:
content = file.read()
# Look for Status information
if "Status:Completed|" in content:
results.append([folder_name, "Success"])
else:
results.append([folder_name, "Failed - Status mismatch"])
except Exception as e:
results.append([folder_name, f"Failed - Read error: {str(e)}"])
# Save results
df = pd.DataFrame(results, columns=["Folder Name", "Status"])
df.to_excel("runlog_status.xlsx", index=False)
print(f"Processing completed! Checked {len(results)} folders")
return df
使用说明:
- 安装依赖:
pip install pandas openpyxl - 使用方法:
- 运行程序后,输入根目录路径
- 程序会自动遍历所有子文件夹
- 检查每个文件夹中的runlog.txt文件
- 生成包含结果的Excel文件
- 输出格式:
Excel文件包含两列:- 文件夹名称
- 状态(成功/失败及具体原因)

被折叠的 条评论
为什么被折叠?



