Python:列表分配超出范围

Python:列表分配超出范围,python,list,error-handling,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()

这个模块是我用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

我可以向模块中添加什么,以便提示用户输入范围内的项目?我想可能是一个试块。。。或者是否有方法捕获异常。。我猜有一个简单的方法可以做到这一点…

在索引时捕获索引器或事先检查列表的
len()

首先阅读文件,然后循环询问用户,直到答案可以接受:

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
为True时:
get\u item=int(原始输入(“\n输入要删除的项目编号:\n”))
如果get_item>=0且get_item

当然,当文件为空并且没有向用户提供任何关于可接受值的提示时,这将中断。但是,让我们为您保留一些练习。

对当前代码进行明智的更改:

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()
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()
def deleteitem():
showlist()
将open(“todo.txt”)作为f:
行=f.读行()
如果len(line)==0:#文件完全为空
返回#适当处理
prompt=“输入要删除的编号(1-%d),或输入要中止的编号:”%len(行)
尽管如此:
输入=原始输入(提示)
尝试:
输入=int(输入,10)
除值错误外:
打印“无效输入”
其他:

如果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()
def deleteitem():
showlist()
f=打开('todo.txt')
行=f.读行()
f、 关闭()
如果len(行)==0:
打印“文件为空!”
返回错误
打印“文件有%d个项目\n”%len(行)
项目=0
当项目
为了它的价值。。。。我将把代码放在我的todo.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 ("#######################################")
from\uuuuuu future\uuuuuuu使用\u语句导入
导入系统
导入操作系统
导入文件输入
操作系统(“清除”)
打印(“待办事项清单”)
印刷品(印刷品)
def showlist():
操作系统(“清除”)
打印(“当前待办事项列表”)
3月月日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日(""""))
get_list=open('todo.txt'))
整个列表=获取列表。读取行()
对于范围内的i(len(整个_列表)):
打印i,整个_列表[i]
获取列表。关闭()
3月月日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日(""""))
3月月日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日(""""))
def appendlist():
3月月日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日("""))
3月月日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日日("""))
addtolist=str(原始输入(“输入新项目:\n”))
列表=打开('todo.txt','a')
写入列表(str(addtolist))
写入(str('\n'))
关闭列表()
showlist()
def deleteitem():
showlist()
将open(“todo.txt”)作为f:
行=f.读行()
如果len(行)==0:
返回
prompt=“输入要删除的编号或输入要中止的“0”:
尽管如此:
输入=原始输入(提示)
尝试:
输入=int(输入,10)
除值错误外:
打印“无效输入”
其他:

如果0添加一个很好的输出,向用户说明问题。裸例外有一些有效的用途,但这不是其中之一。但对于他的目的来说,它就足够了,它完成了任务。还有评论吗?不,没有。例如,如果你运气不好在正确(或错误)的时间得到它,它会默默地吞下键盘中断。我尽可能地设计我的代码,使其即使在这种“不幸”的情况下也能按预期和期望工作,并且在道德上不能推荐此代码。你纠正它有那么难吗?将“exception:”更改为“exception Indexer:”。
exception
捕获所有异常,那么您所说的无声“吞咽”键盘中断是什么意思。@levis:KeyboardInterrupt是一个异常,在这种情况下捕获是错误的。您的代码没有将异常传递给上,而是忽略/吞并它——隐藏它曾经存在过。谢谢,这很有效。我正在使用Python2.5.x,所以我被挂断了“with”。我在脚本中添加了“from future\uuuu import\uuuuu with_statement”,一切都设置好了。我认为在您的代码中,“if len(lines)==0:”行可能需要缩进。。。在我犯错误之前,我一直在犯错误that@skylarking:它不需要缩进,而且那部分应该可以很好地工作,就像我上面说的那样。也许你不小心弄错了?那很可能是我弄错了。。。。如果你好奇的话,我确实在这里发布了完整的todo应用程序作为答案。我相信那里也会有很多改进。你要么是混合了标签和空格,要么是在发布时缩进搞砸了。我想我选择了trifecta,并成功地做到了这三件事。。只是编辑它来清理它。