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,所以顯然我有一些問題讓他們正確積累。
如果你想弄清楚出了什麼問題,首先嚐試**不**捕捉異常,以便你可以看到回溯。 – 2012-03-26 04:53:21