2017-02-15 82 views
0

我必須編寫一個程序,提示用戶輸入六個測試名稱及其分數,並將它們寫入名爲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() 
+1

那麼你'關閉'文件**內'** while'循環?所以下一個迭代。這會失敗... –

回答

0

這就是我所做的。擺脫第二個while while循環,並將閉合文件移出for循環,因爲你正在關閉文件的循環中給你錯誤:(我的一些變量名稱與你的不同,所以請留意)

test_scores = open('tests.txt','w')#open txt file 
print('Entering six tests and scores') 


for count in range(6):#for loop to ask the user 6 times 
    name = input('Enter a test name: ') 
    testscore = int(input('Enter % score on this test: ')) 
    for count2 in range(1): 
     test_scores.write(str(name) + '\n') 
     test_scores.write(str(testscore) + '\n') 
test_scores.close()#close the txt file 
print('File was created successfully!') 
0

塊而:

while name != '': 
 
    ...
這是一個無限循環,如果你的「名」 =「」,所以在第一循環中的文件關閉,第二個!循環你得到一個錯誤