为什么第一个结果没有出现在文件中?

时间:2019-10-22 03:41:19

标签: python python-3.x

我有一个这样的日志文件

  

time1-step1
  time2-step2
  time4-step1
  time6-step3
  time8-step2
  time9-step3

我写了这个python脚本将日志文件转换为xlsx:

import os  
import xlsxwriter

# title
row1 = ["step","1","2","3"]
row2 = ["time"]

def addSheet():
    workbook = xlsxwriter.Workbook('test.xlsx')    
    worksheet = workbook.add_worksheet()
    worksheet.write_row('A1', row1)
    worksheet.write_row('A2', row2)

    with open('test.log', 'r',encoding="utf8", errors='ignore') as f1:
        row = 1
        for line in f1.readlines():
            new_line = line.strip()
            time = str(new_line[0:5])
            col = 1
            if "step1" in new_line:
                print ("step1" , time)
                worksheet.write(row, col, time)
            if "step2" in new_line:
                print ("step2" , time)
                worksheet.write(row, col+1, time)
            if "step3" in new_line:
                worksheet.write(row, col+2, time)
                row += 1
    workbook.close()

if __name__ == '__main__':
    addSheet()

实际结果就像

+----+-----+-----+-----+
|step|  1  |  2  |  3  |
+----+-----+-----+-----+
|time|time4|time2|time6|
|    |     |time8|time9|
+----+-----+-----+-----+

为什么第一个结果“ time1”没有出现在文件中?

1 个答案:

答案 0 :(得分:0)

您的代码有一些逻辑错误。只有当您输入step3

的值时,您才会增加行数

在您的日志文件中-

  

time1-step1
  time2-step2
  time4-step1
  time6-step3
  ...

您在step1之前有2个step3条目。这意味着这行代码-

if "step1" in new_line:
                print ("step1" , time)
                worksheet.write(row, col, time)

time1的条目覆盖time4的条目

您可以通过为每个stepX集使用单独的计数器来解决此问题