2013-04-29 85 views
-1

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') 
+1

到目前爲止你有什麼?這是功課嗎? – dstromberg 2013-04-29 01:20:19

+0

@ user2330409如果是作業,你應該在提問前嘗試一些東西。 SO不是一個完成作業的網站,當你無法正確調試某些內容時,它會提供幫助。 – 2013-04-29 01:26:32

+0

感謝您的迴應,這是作業,我剛剛在上面添加它。那麼我一直在嘗試一段時間,它確實需要調試。對不起,我沒有在帖子中添加代碼。 – user2330409 2013-04-29 01:28:24

回答

0
with open('numbers.txt', 'r') as my_file: 
    try: 
     data = [float(n) for n in my_file.read().split()] 
    except (IOError, ValueError): 
     data = [] 
total = sum(data) 
average = total/len(data) 
print('Numbers: {nums}\nTotal: {total}\nAverage: {average}'.format(nums = data, total = total, average = average)) 

以供將來參考,因爲這是非常簡單的代碼,你可以谷歌的每個部分分別,你可以拼湊他們。

+0

感謝和未來我將使用谷歌,但這令我很沮喪。你給我的代碼幾乎可以工作,但給出了錯誤:\t TypeError:不支持的操作數類型爲+:'int'和'str' – user2330409 2013-04-29 01:37:20

+0

@ user2330409檢查我的編輯(我忘記了讀取文件返回一個字符串)。 – 2013-04-29 02:06:41

+1

非常感謝你!這是有道理的。 – user2330409 2013-04-29 02:09:37