printing to excel file, python
import csv
from math import sqrt
import os
class MaxiAverageCalculator(object):
def __init__(self):
self.ncols = 3
self.nrows = 0
self.s = [0.0, 0.0, 0.0]
self.s2 = [0.0, 0.0, 0.0]
def run(self, fullpath):
with open(fullpath, "rb") as infile:
reader = csv.reader(infile, delimiter=",")
self.colnames = list(next(reader))
assert len(self.colnames) == 3
for row in reader:
L = [ float(x) for x in row ]
assert len(L) == 3
for i, x in enumerate(L):
self.s[i] += x
self.s2[i] +开发者_运维问答= x * x
self.nrows += 1
self.avg = [x/self.nrows for x in self.s]
self.std = [ sqrt((y/self.nrows) - a * a) for a, y in zip(self.avg, self.s2) ]
print "Results for {0}".format(fullpath)
for name, a, s in zip(self.colnames, self.avg, self.std):
f.write(str(a))
f.write(", ")
f.write(str(s))
f.write("\n")
## print "{0}: avg = {1:.5f}, std = {2:.5f}".format(name, a, s)
## print
if __name__ == "__main__":
path="A:\\yoyo\\heyy\\folder"
f=open("A\\yoy\\save.xls")
f.write("xavg, xstd, yavg, ystd, zavg, zstd")
f.write("\n")
dirList=os.listdir(path)
for file in dirList:
fullpath=os.path.join(path,file)
calc = MaxiAverageCalculator()
calc.run(fullpath)
so im trying to print the avg and std for x, y, and z on a separate excel file...i got this script online. but it doesn't seem to work...please help
You still work with flopy disks? Wow :-)
Nevertheless, in one path you write "A:\\..."
, in the other "A\\..."
. Maybe that's it.
Besides, you should explicitly pass f
to run()
. It is better style.
When you do this:
for name, a, s in zip(self.colnames, self.avg, self.std):
f.write(str(a))
f.write(", ")
f.write(str(s))
You aren't separating the previous standard deviation from the next average by a comma or new line in the loop. So suppose your averages are [10, 20, 30] and standard deviations [1, 2, 3]. What gets written into the file will be:
10, 120, 230, 3
If you want it to be:
10, 1, 20, 2, 30, 3
then I'd say a bit of extra code (this might not be the best way to do it but it works):
count = 0
for name, a, s in zip(self.colnames, self.avg, self.std):
count += 1
f.write(str(a))
f.write(", ")
f.write(str(s))
if count < len(self.avg): # If it is not the last record
f.write(", ") # Add a comma separating the std from the next avg
Also why are you zipping the column names at all in the loop? You aren't using it anywhere.
精彩评论