def main():
total = 0.0
length = 0.0
average = 0.0
try:
#Get the name of a file
filename = input('Enter a file name: ')
#Open the file
infile = open(filename, 'r')
#Read the file's contents
contents = infile.read()
#Display the file's contents
print(contents)
#Read values from file and compute average
for line in infile:
amount = float(line)
total += amount
length = length + 1
average = total / length
#Close the file
infile.close()
#Print the amount of numbers in file and average
print('There were ', length, ' numbers in the file.' )
print(format(average, ',.2f'))
except IOError:
print('An error occurred trying to read the file.')
except ValueError:
print('Non-numeric data found in the file')
except:
print('An error has occurred')
main()
我的.txt文件中的数字是这样显示的:78
65
99
88
100
96
76
当我试着跑的时候,我总是得到“发生了一个错误”。在我评论之后,我得到了一个可除性错误。我试着把总数和长度打印出来,看看它们是否真的在计算,但每一个都是0.0,所以很明显,我在让它们正确累积方面遇到了一些问题。