Python 3.x 我試圖讀取一個名爲numbers.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')
到目前爲止你有什麼?這是功課嗎? – dstromberg 2013-04-29 01:20:19
@ user2330409如果是作業,你應該在提問前嘗試一些東西。 SO不是一個完成作業的網站,當你無法正確調試某些內容時,它會提供幫助。 – 2013-04-29 01:26:32
感謝您的迴應,這是作業,我剛剛在上面添加它。那麼我一直在嘗試一段時間,它確實需要調試。對不起,我沒有在帖子中添加代碼。 – user2330409 2013-04-29 01:28:24