如何修复“列表索引超出范围”

时间:2019-07-19 08:22:52

标签: python

我有此索引错误:list index out of range

我在安装了Security Onion的VM上有此问题。当我尝试在PyCharm上使用代码时,它运行良好。

ip = []
mask = []

with open('program.txt') as file:
    for line in file:
        line_words = line.split()
        print(line_words[0])
        ip.append(line_words[0])
        mask.append(line_words[1])

ip = sorted(set(ip))

for i in range(len(ip)):
    x = "block any any -> " + ip[i] + " any " + mask[i]
    with open('final.txt', 'a') as file:
        file.write(x)
        file.write('\n')
        file.close()

我希望有最后一次打印的输出,但是在VM的附加行上伴随着错误。我不知道如何使它工作。

2 个答案:

答案 0 :(得分:1)

line_words[1]中的文本仅包含一个单词时,您的错误来自program.txt

先检查len(line_words)

with open('program.txt') as file:
    for line in file:
        line_words = line.split()
        print(line_words[0])
        if len(line_words) >= 2:
            ip.append(line_words[0])
            mask.append(line_words[1])

答案 1 :(得分:0)

Dorian已经回答了if语句解决方案。另外,您可以尝试使用try / except处理这些错误,并打印所有发生的错误:

for line in file:
    line_words = line.split()
    print(line_words[0])
    try:
        ip.append(line_words[0])
        mask.append(line_words[1])
    except:
        print("The current line does not have enough words: {}".format(line_words)