I think the smallest set of changes that will make this work is:
class TemperatureFile:
def __init__(self, filename):
self.__filename = filename
def getFilename(self):
return self._Filename
def setFilename(self):
self._filename = filename
def calculateAverage(self):
try:
with open(self.__filename,'rb') as temperatureFile:
total = 0
temp = 0
for line in temperatureFile:
amount = float(line.rstrip("\n"))
total += amount
temp = temp + 1
average = total/temp
print(average)
except ValueError as err:
print(err)
except IOError as err:
print(err)
else:
average = total/temp
print(average)
finally:
temperatureFile.close()
def main():
num1 = 35
num2 = 63
num3 = 40
total = 0.0
temp = 0.0
average = 0.0
temperatureFile = open('Temperatures.txt', 'w')
temperatureFile.write(str(num1) + '\n')
temperatureFile.write(str(num2) + '\n')
temperatureFile.write(str(num3) + '\n')
temperatureFile.close()
Temperatures = TemperatureFile('Temperatures.txt')
Temperatures.calculateAverage()
main()
calculateAverage
is a member of the TemperatureFile
class, so it needs to be called on an instance of this class (Temperatures
, here). calculateAverage
takes no arguments. The self
argument is just an explicit version of the implicit this
common in other languages. I moved the opening of the file into the calculateAverage
function since otherwise the __filename
attribute is pointless. I also had to add total
and temp
default definitions.
A more reasonable version [I think], though not strictly conforming to the requirements:
import traceback as tb
class TemperatureFile:
def __init__(self, filename):
self.filename = filename
def calculateAverage(self):
try:
with open(self.filename,'rb') as temperatureFile:
total = 0
temp = 0
for line in temperatureFile:
total += float(line.rstrip("\n"))
temp += 1
print(total/temp)
except:
tb.print_exc()
with open('Temperatures.txt','wb') as output:
output.write(str(35) + '\n')
output.write(str(63) + '\n')
output.write(str(40) + '\n')
TemperatureFile('Temperatures.txt').calculateAverage()
In Python, everything in the root of the file is evaluate/executed by default, so defining a main
function seems a bit uncharacteristic. I also don’t think getters and setters are as common, though not unheard of, since Python is so dynamic anyway. A couple key takeaways: I would recommend using the traceback.print_exc()
function to provide more detailed error messages, and be sure to use with
when opening files to properly handle resource cleanup. Otherwise, I just got rid of some redundant variables that made things somewhat noisy.
4
solved Please Help! I have to read numbers from a text file i create and find the average of these numbers and print it [closed]