【问题标题】:displaying a line of text - exception handling显示一行文本 - 异常处理
【发布时间】:2021-06-21 02:19:04
【问题描述】:

我想输入这样的代码,以便它显示用户指示的行的内容(以从键盘读取的数字的形式)。超出列表范围(行数)时处理异常。 代码如下:

import linecache
try:
    number = int(input("Line: "))
    lines = linecache.getline("text.txt", number)
    print(lines)
except:
    print("no such line was found")

程序正确读取了该行的内容,但是当我要处理异常时,请选择 text.txt 范围之外的一行,例如不存在的第250行,它没有显示异常“没有找到这样的行”,我该如何改进它?

提前致谢!!!

【问题讨论】:

    标签: python file text line except


    【解决方案1】:
    linecache.getline("test.txt", number)
    

    行号不存在时不产生异常,直接返回''

    所以你可以这样做:

    import linecache
    number = int(input("Line: "))
    lines = linecache.getline("text.txt", number)
    print(lines)
    if lines == '':
        print("no such line was found")
    

    【讨论】:

    • 谢谢你的回答,所以不能用try / except块来完成?
    • 使用行 cache.getline 不是我知道的
    猜你喜欢
    • 1970-01-01
    • 2010-12-26
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多