python 较多数据时取均值追加到文件

import re
import sys
import os
import math
from functools import reduce
fileDir = "C:/Users/Administrator/Desktop/data/android/fps/"

file = "s6.txt"
front = 46
stop = 100000
back = 5

output=sys.stdout
def getData():
cpuList = []
rec = 0.0

with open (fileDir+file,'r',encoding='UTF-8') as f:
i = 0
for line in f:
if(i<front):#去掉头
i = i+1
continue
if(i>stop):#终止取值
break
cpustr = line.split(' ')
try:
cpuFloat = float(cpustr[-1])
rec = rec+cpuFloat
cpuList.append(cpuFloat)
except:
print ("转换异常,所在文件行数 = ",len(cpuList)+front)
if(back<=len(cpuList)):
for icpuList in range(back):#去掉尾
rec = rec-cpuList.pop()
f.close()

count = len(cpuList)
if count ==0:
print ("有效数据是0个")
return

print ('file=%s, 行数=%d, front=%d, back=%d'%(file,count,front,back))
average = rec/count
print ("期望 = ",average)

variance = 0.0
for index in range(count) :
variance = variance+(cpuList[index]-average)**2
print ("标准差 = ",variance/count)

offset = math.sqrt(variance/count)*3.29#alpha=0.005时根据t分布得到3.29
u1 = average - offset
u2 = average +offset
print ("区间 = [%f, %f]"%(u1,u2))
cnt = 0
index = 0
rec = 0.0
for index in range(count) :
if(cpuList[index]>u1 and cpuList[index]<u2):
cnt = cnt+1
rec = rec+cpuList[index]
print ("置信区间内的数据均值 = ",rec/cnt)
outputfile=open('C:/Users/Administrator/Desktop/data/s6_value.txt','a')
sys.stdout=outputfile
print (file,' ', rec/cnt)
print ("front=%d,stop=%d,back=%d"%(front,stop,back))
print (" ")
outputfile.close()
sys.stdout=output

if __name__ == '__main__':
getData()

posted @ 2017-10-17 12:01  南柯南  阅读(452)  评论(0编辑  收藏  举报