2017-07-11 37 views
1

這裏是我所做的代碼,更多關於它的內容將在下面進行解釋。ValueError:關閉文件時的I/O操作將結果添加到txt文檔時返回

import os.path 
if os.path.isfile('Times.txt'):  #checks if Times file exists 
    file = open('Times.txt','r+')  #Opens file to read if it does 
    with open('Times.txt','r+') as f: 
     mylist = f.read().splitlines() 
     mylist=[int(x) for x in mylist] 
     mylist.sort() 
     if sum(mylist)!=0: 
      print('Highscore:',mylist[-1],'seconds') 

else: 
    file = open('Times.txt','w')  #Creates file if Times.txt does not exist 
print("Type the alphabet as fast as you can!") #Game code- User types the alphabet as fast as they can. 
time.sleep(1) 
print("3") 
time.sleep(1) 
print("2") 
time.sleep(1) 
print("1") 
time.sleep(1) 
print("GO!!") 
start = time.time() 
alph="" 
while alph != "abcdefghijklmnopqrstuvwxyz": 
    alph=input("") 
    if alph != "abcdefghijklmnopqrstuvwxyz": 
     print("INCORRECT ALPHABET, TRY AGAIN!") 
end = time.time() 
timetaken=(end - start)//1 
Seconds=timetaken 
mins=0 
while timetaken >= 60: 
    timetaken=timetaken-60 
    mins=mins+1 
Time = (mins,"minutes and",timetaken,"seconds") 
print('You took',Time) 
f.write(str(Seconds)) #Adds time to text file 

當我運行的代碼,它返回此錯誤:

Traceback (most recent call last): 
File "C:\Users\johnson.427\Desktop\Adam - Copy\Documents\Adam Homework\SWCHS\YEAR 9\Computing\challenge.py", line 104, in <module> 
c7() 
File "C:\Users\johnson.427\Desktop\Adam - Copy\Documents\Adam Homework\SWCHS\YEAR 9\Computing\challenge.py", line 102, in c7 
f.write(str(Seconds)) 
ValueError: I/O operation on closed file. 

這是我做了一個代碼,任務是:
算法
告訴他們按下回車鍵準備好時的鑰匙
第一次在幾秒鐘內(和分鐘)
讓他們鍵入字母並按回車鍵
獲得第二個時間,以秒(和分鐘)
檢查它們是否正確輸入然後
減去首次從第二次
告訴他們多少秒了
擴展他們已經進入了字母正確

保持最佳時間記錄。 < ------ 這是我堅持
處理大寫或小寫字母輸入< ------ 我可以做到這一點,我只是不包括它尚未

編輯:有沒有另一種方法來做到這一點,而不使用TXT文檔?

+0

我想這可能是因爲,如果你是第一次做,會有列表中沒有的項目,但我不知道如何解決它。 – AJ123

+0

另外,任何人都可以通知我關於任何其他**明顯**錯誤,將停止代碼正常運行? – AJ123

+0

添加真正高時間的默認高分。這應該防止文件中沒有任何內容 –

回答

0

我的,我的,一團亂七八糟的代碼(沒有違法)......你的主要/當前問題是,你打開with區塊內的文件,所以只要退出該文件就關閉文件句柄with block - 當您嘗試寫入一個關閉的文件句柄時,最終會出現提示的錯誤。

首先,沒有必要保持文件句柄對您的高分檔文件開放,無論如何 - 當您開始「遊戲」時打開並閱讀它並在您想保存時打開並寫入它就足夠了分數。所以,這一切都可以大大簡化爲:

import os.path 
import time 

hiscore = 0 # define our hiscore as 0 in case we want to use it somewhere else 
if os.path.isfile('Times.txt'): # checks if Times.exe file exists 
    with open("Times.txt", "r") as f: # open the file for reading 
     hiscore = int(f.readline().strip()) # read the first line, we'll keep it sorted 
     print('Highscore: {} seconds'.format(hiscore)) 

print("Type the alphabet as fast as you can!") 
for line in ("3", "2", "1", "GO!!"): # we can iterate-print instead of typing everything... 
    time.sleep(1) 
    print(line) 

start = time.time() # keep in mind that on Windows time.clock() is more precise! 
while True: 
    if input("") == "abcdefghijklmnopqrstuvwxyz": # on Python 2.x use raw_input instead 
     break 
    print("INCORRECT ALPHABET, TRY AGAIN!") 
end = time.time() 

delta_time = int(end - start) 
minutes, seconds = delta_time // 60, delta_time % 60 
print("You took {} minutes and {} seconds".format(minutes, seconds)) 
# and now finally write the delta_time to the Times.txt 
with open("Times.txt", "a+") as f: # open Times.txt in read/write mode 
    scores = {int(line.strip()) for line in f} # read all the lines and convert them to ints 
    scores.add(delta_time) # add our current score 
    f.seek(0) # move to the beginning of the file 
    f.truncate() # truncate the rest 
    f.write("\n".join(str(x) for x in sorted(scores))) # write the sorted hiscores 
+0

對不起,我python – AJ123

+0

現在它說: – AJ123

+0

文件「C:\ Users \ johnson.427 \ Desktop \ Adam - Copy \ Documents \ Adam Homework \ SWCHS \ YEAR 9 \ Computing \ challenge.py」,第72行,在c7 hiscore = int(f.readline()。strip())#讀取第一行,我們將保持排序 ValueError:無效文字爲int()與基數10:'' – AJ123

相關問題