Writing to text file in Python - How to print at top of new 2nd column?

507 views Asked by At

This code reads a cell from a series of grid files. I'm eventually going to be readings thousands of cells, so I'd like the statistics to show up at the top of a new second column rather than at the bottom of a long list. Anyone know how I might do this?

enter image description here

import os
from os import listdir
import numpy as np

filePath = r'C:\VMsharedUNLOAD\small_example_NoName_200950mWorkCopy3THIN3-FINAL\test'
files = os.listdir(filePath)
fCellList = [len(files)]

queryCol = 5
queryRow = 15

total = 0
variance = 0

######ValueList######
with open('ofile.txt','a') as ofile:
    for file in files:
        f = open(filePath + '\\' + file)
        fCell = f.readlines()[queryRow].split(" ")[queryCol]
        ofile.write(fCell + '\n')
        fCellList.append(float(fCell))
#######MINIMUM#######     
    minimum = min(fCellList[1:])
    ofile.write('\t' + ' min:' + str(minimum) + '\n')    
#######MAXIMUM#######
    maximum = max(fCellList[1:])
    ofile.write('\t' + ' max:' + str(maximum) + '\n')
#######AVERAGE#######  
    for avgNum in fCellList[1:]:
        total += avgNum
    average = (total) / (len(fCellList) - 1)
    ofile.write('\t' + ' avg:' + str(average) + '\n')
########STDEV########   
    for varNum in fCellList[1:]:
        variance += (average - varNum) ** 2
    stdDev = ((variance) / (len(fCellList) - 2)) ** 0.5
    ofile.write('\t' + ' stdDev:' + str(stdDev))
f.close()
ofile.close()
1

There are 1 answers

1
fferri On

A possible solution is to use itertools.zip_longest() (requires Python 3; for Python 2 use itertools.izip_longest())

import os
from os import listdir
import numpy as np

filePath = r'test'
files = [filepath]
fCellList = [len(files)]

stats = []
out = []

queryCol = 5
queryRow = 15

total = 0
variance = 0

######ValueList######
for file in files:
    with open(filePath + '\\' + file) as f:
        fCell = f.readlines()[queryRow].split(" ")[queryCol]
    out.append(fCell)
    fCellList.append(float(fCell))
#######MINIMUM#######
minimum = min(fCellList[1:])
stats.append('min:' + str(minimum))
#######MAXIMUM#######
maximum = max(fCellList[1:])
stats.append('max:' + str(maximum))
#######AVERAGE#######
for avgNum in fCellList[1:]:
    total += avgNum
average = (total) / (len(fCellList) - 1)
stats.append('avg:' + str(average))
########STDEV########
for varNum in fCellList[1:]:
    variance += (average - varNum) ** 2
stdDev = ((variance) / (len(fCellList) - 2)) ** 0.5
stats.append('stdDev:' + str(stdDev))

with open('ofile.txt','a') as ofile:
    for line in zip_longest(out, stats):
        if not line[1]: line = line[:1]
        ofile.write('\t'.join(line)+'\n')

Also note that if you use the with statement for working with files, you don't have to .close() the file after the with statement.