2015-02-11 66 views
-4

我有一個任務,它是編寫一個程序,其中包含以下菜單項(從文件中讀取): 1-高分顯示 2-添加新的高分 3清除所有的高分 4退出Python - 從文件中排序高分

我已經休息了工作,它只是一個顯示高分。我收到語法錯誤。該錯誤是一個InternalError:列表超出範圍。這裏是代碼的一部分:

def askUser(): 
Question=input('What would you like to do?\n1-Display High Scores\n2-Add A New High Score\n3-Clear All High Scores\n4-Quit\nPlease choose a number:') 
if Question=='1': 
    myFile=open('Scores.txt','r') 
    column=[] 
    for line in myFile: 
     column.append(int(line.split("\t")[3])) 
    column.sort() 
    print(column) 
    myFile.close() 
    askUser() 

這可能仍然沒有意義,從這裏......但。不過,這是我的完整代碼:

def askUser(): 
Question=input('What would you like to do?\n1-Display High Scores\n2-Add A New High Score\n3-Clear All High Scores\n4-Quit\nPlease choose a number:') 
if Question=='1': 
    myFile=open('Scores.txt','r') 
    column=[] 
    for line in myFile: 
     column.append(int(line.split("\t")[3])) 
    column.sort() 
    print(column) 
    myFile.close() 
    askUser() 
if Question=='2': 
    Name=input('What is your name:') 
    Date=input('What is the date:') 
    Score=input('What was your high score:') 
    myFile=open('Scores.txt','a') 
    myFile.write(("\n"+"{},{},{}").format(Name, Date, Score)) 
    myFile.close() 
    askUser() 
if Question=='3': 
    myFile=open('Scores.txt','r+') 
    myFile.truncate() 
    myFile.close() 
    print('File Cleared') 
    askUser() 
if Question=='4': 
    print('Quiting...') 

對不起,如果我不清楚。我需要從文件Scores.txt中顯示高分(選項1)。我已經寫在那裏了幾樣的分數,如果你需要讓他們也試試這個代碼:

Name=input('What is your name:') 
Date=input('What is the date:') 
Score=input('What was your high score:') 
myFile=open('Scores.txt','a') 
myFile.write(("\n"+"{},{},{}").format(Name, Date, Score)) 
myFile.close() 
+2

首先,需要正確的縮進。 其次,嘗試包括您收到的完整錯誤消息。另外, 你可能會發現這個使用:https://stackoverflow.com/help/mcve – 2015-02-11 21:21:23

回答

1

冉代碼:

column.append(int(line.split("\t")[3])) 
IndexError: list index out of range 

我相信你不會分裂右側標準。您使用逗號作爲.. uhh分隔符來生成樂譜文件..但是,然後讓它根據\ t來分割,這是製表符,我相信。將其改爲逗號。此外,python索引從0開始。因此將3(指第4項)設置爲2(指第3項)。

此外,在score.txt的開頭有一個空行(假設您清除分數並添加分數會產生問題)。

做這樣的事情:

for line in myFile: 
     if line == "\n": 
      this = "doesnothing" 
     else: 
      column.append(int(line.split(",")[2])) 

而且搜索返回的錯誤幫助: Python: IndexError: list index out of range

+0

嗯......我仍然得到相同的索引超出範圍的錯誤。 – UserIsMe 2015-02-11 22:02:39

+0

更新了我的答案。 – BruceDarby 2015-02-11 22:03:31

+0

非常感謝。你幫助我難以置信! – UserIsMe 2015-02-11 22:11:36

1

你只提到你得到了「語法錯誤」與您的代碼,但實際上並沒有說哪你得到的錯誤,但基於代碼片段,我會說你沒有得到正確的縮進:在def之後應該有一個縮進塊。