2017-04-14 94 views
2

你好,我是比较新的编程和我不知道为什么我收到以下错误: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") 

任何有识之士将不胜感激。

回答

1

我意思是x是只有一个元素的列表。这种情况很可能是因为在那里的(由holder)定义的行中:

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

holder只是长度为1的在一些特定line。您可以通过添加

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