2016-08-03 90 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))