为什么下面的代码在“ break”之后停止?如果我在“ break”之后插入打印语句,则会打印出来(例如,打印“ done!”)。为什么在“休息”后不能在open ..下运行?它们各自独立工作(作为独立的.py文件)。
diskDetails = open("diskDetails.txt", "r")
data = open("data.txt", "w")
searchlines = diskDetails.readlines()
for i, line in enumerate(searchlines):
if "Failed" in line:
for l in searchlines[i-3:i+25]: print >> data, l
print
break
with open('data.txt') as infile, open('dataFinal.txt', 'w') as outfile:
for line in infile:
if line.startswith(("ID", "State", "Capacity", "Product ID", "----")):
outfile.write(line)
dataFinal.txt文件为空白,因此在“中断”之后似乎停止了。难道不是“中断”只是停止了“ if”循环?为什么要打印“完成!”但不是'with open('data.txt')....部分?
diskDetails.txt包含几条记录,每条记录长27行(本示例中我已缩短):
ID : 0:1:6
Status : Non-Critical
Name : Physical Disk 0:1:6
State : Failed
Power Status : Spun Up
Bus Protocol : SAS
Media : HDD
Part of Cache Pool : Not Applicable
Remaining Rated Write Endurance : Not Applicable
Failure Predicted : Yes
Revision : ES66
Driver Version : Not Applicable
Model Number : Not Applicable
T10 PI Capable : No
Certified : Yes
代码的第一部分获取包含“ Failed”(失败)的记录(查找失败,并返回上方(i-3)的2行和下方(i + 25)的25行,并将其输出到名为“ data”的文件中。 txt”。
代码的第二部分(打开...)获取该data.txt文件,查找特定行(包含ID,State,Capacity等)并将其打印到名为dataFinal.txt的文件中
cat dataFinal.txt
ID : 0:1:6
State : Failed
Capacity : 558.38 GB (599550590976 bytes)
Product ID : ST3600057SS
这两个代码部分可以独立正常工作(如上所示)。如何使它们在同一.py文件中一起工作? 谢谢!
答案 0 :(得分:1)
好的,最后我将您的代码分为三个部分:
result = []
# 1. Search for the first failed entry:
with open('diskDetails.txt', 'r') as f:
lines = f.readlines()
for idx, line in enumerate(lines):
if ': Failed' in line:
result = lines[idx-3:idx+12] # save lines from 'ID' to 'Certified'
break # only the first match
# 2. Filter result:
keywords = ('ID', 'State', 'Capacity', 'Product ID')
result = list(filter(lambda l: str(l).startswith(keywords), result))
# 3. Save result:
with open('dataFinal.txt', 'wt') as f:
f.writelines(result)
# $ cat dataFinal.txt
# ID : 0:1:6
# State : Failed