Python 3.x版 我试图从一个名为数字.txt. 里面有几行数字。我需要打印总数和平均数。除此之外,我还需要对IOerror和ValueError使用异常处理。在
提前谢谢你。我知道这是一个错误的建议。在
def main():
total = 0.0
length = 0.0
average = 0.0
try:
filename = raw_input('Enter a file name: ')
infile = open(filename, 'r')
for line in infile:
print (line.rstrip("\n"))
amount = float(line.rstrip("\n"))
total += amount
length = length + 1
average = total / length
infile.close()
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')
为了将来的参考,因为这是一个相当简单的代码,你可以单独谷歌每个部分,你可以拼凑起来。在
相关问题 更多 >
编程相关推荐