我必須編寫一個程序,它將讀取文件中的數據,將其轉換爲整數和總量。到目前爲止,這是我的。數據文件「numdata.txt」中的數字是:78,93,85,100,81,76,94,77。從Python中的文件中讀取數據異常
def main():
total = 0
try:
NumberFile = open('numdata.txt', 'r')
for line in NumberFile:
amount = float(line)
total += amount
print(format(total, ',.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.')
finally:
NumberFile.close()
main()
當我運行的第一個數字(78)被顯示的程序,然後異常錯誤消息之一出現時,奇怪的事情是,它是不同的,有時。如果有人能幫助我指出正確的方向,我會很感激。我對這個還很陌生,所以請耐心等待。
我試了又試,但不能得到循環才能正常工作,所以我結束了走這條路:
def main():
infile = open('numdata.txt', 'r')
num1 = int(infile.readline())
num2 = int(infile.readline())
num3 = int(infile.readline())
num4 = int(infile.readline())
num5 = int(infile.readline())
num6 = int(infile.readline())
num7 = int(infile.readline())
num8 = int(infile.readline())
infile.close()
total = num1+num2+num3+num4+num5+num6+num7+num8
average = total/8
print('the total: ', total)
print('the average: ', average)
的main()
它不漂亮,但它的工作原理我想笑
能否請您重新格式化您的代碼? – mdegis
抱歉,我沒有看到您的評論,我想我做了你所問的? – hppylttletrees