2012-03-26 83 views
0
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文件的數字顯示方式:計算從數字中的.txt文件平均使用Python

78 
65 
99 
88 
100 
96 
76 

我不斷收到「發生錯誤」,當我嘗試運行。在我發表評論後,我得到一個可分性錯誤。我試圖打印出總計和長度,看他們是否真的在計算,但每個都是0.0,所以顯然我有一些問題讓他們正確積累。

+0

如果你想弄清楚出了什麼問題,首先嚐試**不**捕捉異常,以便你可以看到回溯。 – 2012-03-26 04:53:21

回答

2

infile.read()消耗該文件。考慮寫每一行代替你碰到它。

2

infile.read()將採取整個文件,而不是個別部分。如果你想要單獨的部分,你必須將它們分開(空間),並擺脫空白(即\n)。

強制性的一行:

contents = infile.read().strip().split() 

這樣,你會希望遍歷的contents的內容,因爲這是唯一值得迭代。 infile已耗盡,隨後調用read()將生成一個空字符串。

for num in contents: 
    amount = float(num) 
    # more code here 

average = total/len(contents) # you can use the builtin len() method to get the length of contents instead of counting yourself 
+1

代碼已經在文件中正確迭代了文件中的行;它只是需要避免消耗文件。 – 2012-03-26 04:54:59

0

我修改了你的代碼,看看我是否可以使它工作,仍然看起來像你的儘可能多。這是我想出的:

def main(): 

total = 0.0 
length = 0.0 
average = 0.0 

    try: 
     #Get the name of a file 
     filename = raw_input('Enter a file name: ') 

     #Open the file 
     infile = open(filename, 'r') 

     #Read values from file and compute average 
     for line in infile: 
      print line.rstrip("\n") 
      amount = float(line.rstrip("\n")) 
      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()