简体   繁体   English

如何错误检查列表索引超出范围

[英]How to error check list index out of range

I have a read.log file that will have lines such as... 我有一个read.log文件,其中包含如下行:

10.2.177.170 Tue Jun 19 03:30:55 CDT 2018
10.2.177.170 Tue Jun 19 03:31:03 CDT 2018
10.2.177.170 Tue Jun 19 03:31:04 CDT 2018
10.2.177.170 Tue Jun 19 03:32:04 CDT 2018
10.2.177.170 Tue Jun 19 03:33:04 CDT 2018

My code will read the 3rd to last line and combine strings. 我的代码将读取第三行到最后一行并组合字符串。 So the normal output would be: 因此,正常输出为:

2018:19:03:32:04

My problem is, if there are only 4 or less lines of data such as 我的问题是,如果只有4条或更少的数据行,例如

10.1.177.170 Tue Jun 19 03:30:55 CDT 2018
10.1.177.170 Tue Jun 19 03:31:03 CDT 2018
10.1.177.170 Tue Jun 19 03:31:04 CDT 2018
10.1.177.170 Tue Jun 19 03:32:04 CDT 2018

I get an error 我得到一个错误

    x1 = line.split()[0]
IndexError: list index out of range

How can I error check this or keep it from happening? 如何进行错误检查或阻止它发生? I have been trying to check how many lines there are in the log and if less than 5, print a notice. 我一直在尝试检查日志中有多少行,如果少于5行,请打印一条通知。 Are there better options? 有更好的选择吗?

def run():

    f = open('read.log', 'r')
    lnumber = dict()
    for num,line in enumerate(f,1):  
        x1 = line.split()[0]
        log_day  = line.split()[3]
        log_time = line.split()[4]
        log_year = line.split()[6]
        if x1 in lnumber:
            lnumber[x1].append((log_year + ":" + log_day + ":" + log_time))
        else:
            lnumber[x1] = [(num,log_time)]

    if x1 in lnumber and len(lnumber.get(x1,None)) > 2:

        # if there are less than 3 lines in document, this will fail

        line_time = (lnumber[x1][-3].__str__())
        print(line_time)
    else:
        print('nothing')
    f.close

run()

f.readlines() gives you a list of lines in a file. f.readlines()为您提供文件中的行列表。 So, you could try reading in all the lines in a file: 因此,您可以尝试读取文件中的所有行:

f = open('firewall.log', 'r')
lines = f.readlines()

And exiting if there are 4 or less lines: 如果有4行或更少的行,则退出:

if len(lines) <= 4:
    f.close()
    print("4 or less lines in file")
    exit()

That IndexError you're getting is because you're calling split() on a line with nothing on it. 您得到的那个IndexError是因为您在没有任何内容的一行上调用split() I would suggest doing something like if not line: continue to avoid that case. 我建议做一些事情, if not line: continue避免这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM