【发布时间】:2025-12-09 17:20:03
【问题描述】:
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,所以显然我在让它们正确累积方面遇到了一些问题。
【问题讨论】:
-
如果你想弄清楚哪里出了问题,首先尝试not捕获异常,这样你就可以看到回溯。
标签: python file python-3.x