我必須編寫一個程序,提示用戶輸入六個測試名稱及其分數,並將它們寫入名爲tests.txt的文本文件。您必須使用循環。每個輸入都應該寫入文件中它自己的行。該程序應該在完成時生成確認消息。當我運行我的程序它的工作原理,但然後我得到一個最後的錯誤說:在Python中關閉文件的I/O操作
Traceback (most recent call last):
File "C:/Users/brittmoe09/Desktop/program6_1.py", line 34, in <module>
main()
File "C:/Users/brittmoe09/Desktop/program6_1.py", line 18, in main
test_scores.write(name + '\n')
ValueError: I/O operation on closed file.
我不知道我在做什麼錯了,任何幫助,將不勝感激。
這裏是我的代碼:
def main():
test_scores = open('tests.txt', 'w')
print('Entering six tests and scores')
for count in range(6):
name = input('Enter a test name')
score = int(input('Enter % score on this test'))
while name != '':
test_scores.write(name + '\n')
test_scores.write(str(score) + '\n')
test_scores.close()
print('File was created successfully')
main()
那麼你'關閉'文件**內'** while'循環?所以下一個迭代。這會失敗... –