Python:列表分配超出范围

时间:2010-03-11 14:11:05

标签: python list error-handling

这个模块是我用Python制作的简单todo应用程序的一部分......

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

我可以在模块中添加什么以便提示用户输入范围内的项目?我假设可能是一个试块......或者有没有办法捕捉异常......我猜有一种简单的方法可以做到这一点......

6 个答案:

答案 0 :(得分:3)

在编制索引时捕获IndexError或预先检查列表的len()

答案 1 :(得分: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

当然,这将在文件为空时中断,并且不会向用户提供有关可接受值的任何提示。但是,让我们为你做一些运动。

答案 2 :(得分: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()

答案 3 :(得分: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()

答案 4 :(得分: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()

答案 5 :(得分:0)

对于它的价值......我会把代码放到我的todo.py程序中......这只是我从OS X的终端运行以控制我在工作中需要做的事情。 ..我相信它非常恐怖,效率低下以及其他一切......但也许它会对一个偶然发现这个线程的人有用:

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 ("#######################################")