首页 > 解决方案 > Script not logging last element of a list into a csv file

问题描述

I have a Python class (TimeTesting) which has 3 methods inside it -

  1. TimeTest1 - Gets the current time and introduces a sleep of 1 second.
  2. TimeTest2 - Gets the current time and calculates the difference between time obtained in TimeTest1 and the time obtained in the function TimeTest2.
  3. LogOperation - Logs the operation to a csv file with the headers being IterationNumber, T1Value, T2Value and TimeDifference.

I am running all the three functions in a loop for 10 times. But the last iteration (i.e. the 10th one) is not being captured in the log file. Below is my code.

import datetime
from datetime import timedelta
import time
import csv
import collections

MyVar1 = range(1,11)
DataList = []

class TimeTesting:
    def TimeTest1(self):
        self.T1 = datetime.datetime.now()
        time.sleep(1)
        self.LogFileHeader = ['IterationNumber', 'T1Value', 'T2Value', 'TimeDifference']
        print('TimeTest1 function called')

    def TimeTest2(self):
        self.T2 = datetime.datetime.now()
        self.TimeDiff = self.T2 - self.T1
        print('Timetest2 function called')

    #Log operation function
    def LogOperation(self, Var1):        
        with open('LogFile.csv', 'w') as LogList:
            write = csv.writer(LogList, delimiter = "|", lineterminator = "\n") 
        
            #Extracting the header from the log file
            with open('LogFile.csv', 'r') as ReadLogFile:
                reader = csv.DictReader(ReadLogFile)
                fieldnames = reader.fieldnames
                FileHeaderStringFormat = str(fieldnames)

            #Converting the header from the TimeTest1 function
            TempResult1 = str(self.LogFileHeader)
            LogHeaderStringFormat = TempResult1.replace("', '", "|")

            #Comparing FileHeaderStringFormat and LogHeaderStringFormat
            a = set(FileHeaderStringFormat)
            b = set(LogHeaderStringFormat)  
  
            if collections.Counter(a) == collections.Counter(b):
                write.writerows(DataList)
                DataList.append((Var1, self.T1, self.T2, self.TimeDiff))
            else:
                write.writerow(self.LogFileHeader)
                write.writerows(DataList)
                DataList.append((Var1, self.T1, self.T2, self.TimeDiff))


ob = TimeTesting()

for item in MyVar1:
    ob.TimeTest1()
    ob.TimeTest2()
    ob.LogOperation(item)

Below is the log file that is being generated.

enter image description here

标签: pythonpython-3.x

解决方案


These lines

 write.writerow(self.LogFileHeader)
 write.writerows(DataList)
 DataList.append((Var1, self.T1, self.T2, self.TimeDiff))

if you rewrite them as

 DataList.append((Var1, self.T1, self.T2, self.TimeDiff))
 write.writerow(self.LogFileHeader)
 write.writerows(DataList)

You were appending the list after you write the row.


推荐阅读