2010-03-11 94 views
0

這個模塊是一個簡單的待辦事項應用程序,我與Python做的一部分......的Python:列表賦值超出範圍

def deleteitem(): 
      showlist() 
      get_item = int(raw_input("\n Enter number of item to delete: \n")) 
      f = open('todo.txt') 
      lines = f.readlines() 
      f.close() 
      lines[get_item] = "" 
      f = open('todo.txt','w') 
      f.writelines(lines) 
      f.close() 
      showlist() 

F中的行數明顯變化項目添加到列表中..這裏的問題是,例如如果在只有9個文件中的行(或其他任何不在範圍內),用戶輸入「10」,退出預期有:

IndexError: list assignment index out of range 

我可以添加到什麼該模塊,以便它提示用戶輸入範圍內的項目?我假設可能是一個嘗試塊...或者是有一種方法來捕捉異常..我猜測有一個簡單的方法來做到這一點...

回答

1

明智更改當前代碼:

def deleteitem(): 
    showlist() 

    with open("todo.txt") as f: 
    lines = f.readlines() 
    if len(lines) == 0: # completely empty file 
    return # handle appropriately 
    prompt = "Enter number to delete (1-%d), or 0 to abort: " % len(lines) 
    while True: 
    input = raw_input(prompt) 
    try: 
     input = int(input, 10) 
    except ValueError: 
     print "Invalid input." 
    else: 
     if 0 <= input <= len(lines): 
     break 
     print "Input out of range." 
    if input == 0: 
    return 
    input -= 1 # adjust from [1,len] to [0,len) 

    #del lines[input] # if you want to remove that line completely 
    lines[input] = "\n" # or just make that line blank (what you had) 

    with open("todo.txt", "w") as f: 
    f.writelines(lines) 

    showlist() 
+0

謝謝,這工作。 我正在使用Python 2.5.x ..所以我越來越掛在'與'。 我在腳本中添加了「from future__import__ with_statement」並全部設置完畢。 我想在你的代碼中,行 「if len(lines)== 0:」 可能需要縮進? ...直到我這麼做,我得到一個錯誤 – cit 2010-03-11 15:41:52

+0

@skylarking:它不應該需要縮進,並且該部分應該正常工作,因爲我上面有它。也許你不小心誤會了? – 2010-03-11 15:44:44

+0

這很可能導致我犯了一個錯誤......如果您好奇,我確實在此發佈完整的待辦事項應用程序作爲答案。我確信有很多改進可能會發生在那裏 – cit 2010-03-11 16:24:57

3

要麼捕捉IndexError索引或檢查len()的預先列出。

3

首先讀取該文件,然後要求用戶在一個循環,直到答案是可以接受的:

while True: 
    get_item = int(raw_input("\n Enter number of item to delete: \n")) 
    if get_item >=0 and get_item < len(lines): 
     break 

這將,當然,休息的時候該文件是空的,並沒有給出任何的暗示可接受的值給用戶。但讓我們爲你保留一些鍛鍊。

+0

添加一個很好的輸出來向用戶說明問題。 – 2010-03-11 14:26:25

0
def deleteitem(): 
      showlist() 
      get_item = int(raw_input("\n Enter number of item to delete: \n")) 
      f = open('todo.txt') 
      lines = f.readlines() 
      f.close() 
      try: 
       lines[get_item] = "" 
      except Exception,err: 
       print err 
      f = open('todo.txt','w') 
      f.writelines(lines) 
      f.close() 
      showlist() 
+0

裸除了有一些有效的用途,但這不是其中之一。 – 2010-03-11 14:29:58

+0

但它足以達到他的目的,並且它完成了這項工作。還有什麼意見? – ghostdog74 2010-03-11 15:05:10

+1

不,它沒有。它會默默吞下KeyboardInterrupt,例如,如果你不幸在正確(或錯誤)的時間得到它。儘可能地,我設計我的代碼,使其即使在這樣的「不幸」情況下也能按預期和期望工作,並且不能道德上推薦此代碼。你糾正它甚至很難嗎?將「except:」更改爲「除IndexError:」外。 – 2010-03-11 15:36:44

0

嘗試是這樣的:

def deleteitem(): 

showlist() 
f = open('todo.txt') 
lines = f.readlines() 
f.close() 
if len(lines) == 0: 
    print "File is empty!" 
    return False 
print "File has %d items\n" % len(lines) 
item = 0 
while item < len(lines): 
    item = raw_input("\n Enter number of item to delete(0-%d): \n" % len(lines)) 
    item = int(item) # because of the width of the code 
f = open('todo.txt','w') 
f.write(lines[0:item-1]) 
f.write(lines[item::]) 
f.close() 
showlist() 
0

對於它的價值....我把代碼給我的待辦事項.py程序在這裏......這只是我從OS X的一個終端運行來保持我在工作中需要做的事情的控制......我確定它是可怕的非pythonic,低效率和其他一切......但也許這對某個在這個線程中發現的人會有用處:

from __future__ import with_statement 
import sys 
import os 
import fileinput 

os.system('clear') 

print ("##############   TO DO LIST  ############") 
print ("##############       ############") 

def showlist(): 
    os.system('clear') 
    print ("############ Current To Do List ######") 
    print ("########################################") 

    get_list = open('todo.txt') 
    entire_list = get_list.readlines() 
    for i in range (len(entire_list)): 
     print i, entire_list[i] 
    get_list.close() 
    print ("########################################") 
    print ("########################################") 

def appendlist(): 
    print ("#######################################") 
    print ("#######################################") 


    addtolist = str(raw_input("Enter new item: \n")) 
    thelist = open('todo.txt', 'a') 
    thelist.write(str(addtolist)) 
    thelist.write(str('\n')) 
    thelist.close() 
    showlist() 


def deleteitem(): 
    showlist() 

     with open("todo.txt") as f: 
      lines = f.readlines() 
      if len(lines) == 0: 
       return 
     prompt = "Enter number to delete or '0' to abort: " 
     while True: 
       input = raw_input(prompt) 
       try: 
        input = int(input, 10) 
       except ValueError: 
        print "Invalid input." 
       else: 
        if 0 <= input <= len(lines): 
         break 
        print "Input out of range." 
     if input == 0: 
        return 

     lines[input] = "" 

      with open("todo.txt", "w") as f: 
       f.writelines(lines) 

     showlist() 

while True: 

    askme = raw_input("\nDo you want to:\n(S)ee list\n(A)ppend list\n(D)elte from list\n(Q)Quit?\n") 
    print str('\n') 

    if askme == "S": 
     showlist() 
    elif askme == "A": 
     appendlist() 
    elif askme == "D": 
     deleteitem() 

    elif askme == "Q": 
     sys.exit() 
    else: 
     print ("Try again?") 

print ("#######################################") 
print ("#######################################") 
+0

您要麼混合標籤和空格,要麼在縮小到張貼在SO上時被搞砸了。 – 2010-03-11 16:46:59

+0

我想我去了trifecta,並設法做所有這三件事.. 只是編輯它來清理它。 – cit 2010-03-11 17:21:19