2016-08-03 104 views
0

当我试图扫描/搜索的文件,它抛出:Python的IndexError扫描文件

IndexError: list index out of range on the line "list = self.scanFolder(path[t])"

这是一个对象,并有一些方法/函数这里没有显示,因为它们是不相关的这段代码。

def scanFolder(self, path): 
    try: 
     return os.listdir(path) 
    except WindowsError: 
     return "%access-denied%" 

def separate(self, files): 
    #Give Param of Files with exact path 
    file = [] 
    dir = [] 
    for x in range(len(files)): 

     if os.path.isfile(files[x]): 

      file.append(files[x]) 

    for x in range(len(files)): 
     if os.path.isdir(files[x]): 
      dir.append(files[x]) 
    return file, dir 

    def startScan(self): 
    driveLetters = self.getDrives() 
    matches = [] 
    paths = [] 
    paths2 = [] 
    path = "C:/" 
    list = self.scanFolder(path) 

    if list != "%access-denied%": 
     for i in range(len(list)): 
      list[i] = os.path.join(path, list[i]) 

     files, dirs = self.separate(list) 
     paths2.extend(dirs) 
     for i in range(len(files)): 
      if files[i].lower() in self.keyword.lower(): 
       matches.append(files[i]) 

     paths = [] 
     paths = paths2 
     paths2 = [] 
    while paths != []: 
     for t in range(len(paths)): 

      print(paths) 
      print(t) 
      list = self.scanFolder(paths[t]) 
      if list != "%access-denied%": 
       for i in range(len(list)): 
        list[i] = os.path.join(paths[t], list[i]) 

       files, dirs = self.separate(list) 
       if dirs != []: 
        paths2.extend(dirs) 
       for i in range(len(files)): 
        if files[i].lower() in self.keyword.lower(): 
         matches.append(files[t]) 

       paths = paths2 
       paths2 = [] 

    return matches 

回答

1

您正试图访问无效位置。

for t in range(len(paths)): 
    print(paths) 
    print(t) 
    list = self.scanFolder(paths[t]) 

有效的列表索引0..len(路径)-1

你应该访问列表元素,以更Python形式:

for path in paths: 
    list = self.scanFolder(path) 

如果你需要改变一些列表元素,您应该使用enumerate()

for pos, path in enumerate(paths): 
    print ("paths[%s] = %s" %(pos, path))