I need to read info from external file, and then get the averages. The code is meant to work with any length for each month. I have the first average working but the rest won’t. Help would be appreciated.
tempData = open(r"D:\Grade 11\Computer Science\Temperature Data.txt", "r")
array = tempData.read().splitlines()
tempData.close()
avgData = open(r"D:\Grade 11\Computer Science\Average Temperature.txt", "w")
div = 0
total = 0
for data in array:
try:
temp = float(data)
total += temp
div += 1
avg = total / div
except:
month = data
try:
avgData.writelines(str(avg) + "\n")
except:
avgData.writelines(data + "\n")
div = 0
total = 0
avgData.close()
avgData = open(r"D:\Grade 11\Computer Science\Average Temperature.txt", "r")
print(array)
print(avgData.read())
I see you are writing to D:\Grade 11\Computer Science\Average Temperature.txt and then reopening that file to write its contents to the console. Does that file contain the right results but the console doesn’t?
Ok I finally got it to work. Here is the code for anyone else who has the same problem:
#Opens the file with the data
tempData = open(r"D:\Grade 11\Computer Science\Temperature Data.txt", "r")
#Inserts the data into an array
array = tempData.read().splitlines()
#Close the file
tempData.close()
#Opens a file to save averages into
avgData = open(r"D:\Grade 11\Computer Science\Average Temperature.txt", "w")
#Defines variables
total = 0
avgtemp = []
#Loop so it functions for any amount of values
for data in array:
#Works to get the averages and split when there is a new month
try:
temp = float(data)
total += temp
avgtemp.append(temp)
except:
try:
avg = total / len(avgtemp)
avgtemp = []
avgData.writelines(str(avg) + "\n")
finally:
avgData.writelines(data + "\n")
total = 0
continue
avg = total / len(avgtemp)
avgData.writelines(str(avg) + "\n")
avgData.close()
#Reopens the file so it can print the results
avgData = open(r"D:\Grade 11\Computer Science\Average Temperature.txt", "r")
print(avgData.read())
avgData.close()
Don’t use ‘bare’ excepts. They’ll catch all exceptions, even NameError if you happened to misspell a name. Catch only what you’re going to handle.
It doesn’t write out the last average because it writes that only when it catches an exception, which won’t occur when it happens to reach the end of the input file.
Whenever it writes the average it resets div to 0, so, if div isn’t 0 when it reaches the end of the file, it needs to write out the final average.
If div happens to be 0 at the end, you don’t write to write the average because dividing by 0 will give you an exception.