Python索引超出范围错误,不确定原因

2024-06-16 14:11:04 发布

您现在位置:Python中文网/ 问答频道 /正文

您好,我对编程比较陌生,不知道为什么会出现以下错误:

C:\Python34\python.exe C:/Users/ub62357.UBOC-AD/.PyCharmCE2017.1/config/scratches/scratch.py
3.1.1   Status of the 'Minimum Password Length' setting
Pass: 14 or greater
Fail: 13 or less, or missing
Found:set password-controls min-password-length

 line 42, in <module>
    print(x[1])
IndexError: list index out of range

Process finished with exit code 1

我知道索引是从0开始的。我想我相应地调整了代码。我有一个记事本文件,其中有4(0-3)个字段用|分隔。你知道吗

代码应该在另一个文件中搜索第三个索引,并在找到该文件后显示与其他索引关联的信息。你知道吗

这是我的代码(减去导入):

'''
I. Creates a list that stores the files in the folder where the configuration files are stored. Currently it is searching for all the text files
II. Loops through and opens that file so it can be tested.
'''
#creates a list to store the names of the configuration files to be tested
file_list = []
#fills the list with the files in the specified directory
for filename in os.listdir('C:\\Users\\ub62357.UBOC-AD\\Desktop\\FW ComplianceII\\Test Config\\'):
    if filename.endswith(".txt"):
           file_list.append(filename)
    # Creates comparison list
    Comparison_list = []
    # Opens the master file for comparison
    f_master = open('C:\\Users\\ub62357.UBOC-AD\\Desktop\\FW ComplianceII\\TSS_Script_List.txt', 'r')
    # Stores and splits the output and search information
    for line in f_master:
        holder = line.split("|")
        holder = [x.strip() for x in holder]
        Comparison_list.append(holder)
    # Loops through the files
    for i in range(len(file_list)):
        # appends the filename to the directory name and opens the file
        c_file = open('C:\\Users\\ub62357.UBOC-AD\\Desktop\\FW ComplianceII\\Test Config\\'+(file_list[i]))
        for x in Comparison_list:
               for line in c_file:
                    search_criteria = line.find(x[3])
                    if search_criteria == 0:
                        print(x[0])
                        print(x[1])
                        print(x[2])
                        print("Found:" + x[3])
        else:
            print(x[0])
            print(x[1])
            print(x[2])
            print("Line not found")

任何见解都将不胜感激。你知道吗


Tags: andtheinforlinefilesfilenameusers
1条回答
网友
1楼 · 发布于 2024-06-16 14:11:04

这意味着x是一个只有一个元素的列表。这很可能是因为在定义它的行中(由holder):

    holder = [x.strip() for x in holder]
    Comparison_list.append(holder)

holder在某些特定的line中仅为长度1。你可以通过添加

if len(holder)==1:
    `print(line)`

相关问题 更多 >