python - Script not logging last element of a list into a csv file
问题描述
I have a Python class (TimeTesting
) which has 3 methods inside it -
TimeTest1
- Gets the current time and introduces a sleep of 1 second.TimeTest2
- Gets the current time and calculates the difference between time obtained inTimeTest1
and the time obtained in the functionTimeTest2
.LogOperation
- Logs the operation to a csv file with the headers beingIterationNumber
,T1Value
,T2Value
andTimeDifference
.
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.
解决方案
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.
推荐阅读
- android - 刷新片段不调用 onCreate()。这是正常的?
- haskell - 关于hackerRank关于字母和权重的解决方案的建议
- firebase - 不同的项目名称和应用显示名称对部署的影响
- ruby-on-rails - 在工作人员中设置asset_host
- c# - 字段 *** 从未分配给,并且将始终具有其默认值 null selenium page factory
- python - 检查目标时出错:预期 dense_3 的形状为 (4,) 但得到的数组的形状为 (10,)
- reactjs - 映射 Axios 响应并将第 2 个 Axios 响应附加到第 1 个
- javascript - 函数参数是 Typescript 类型中存在的属性
- java - 即使我认为它的设置正确,我的 super 也无法正常工作
- javascript - LocalStorage 被重置/丢失