扫描文件时的Python IndexError

时间:2016-08-03 23:53:22

标签: python list indexoutofboundsexception iterable

我正在尝试扫描/搜索文件并抛出:

  

IndexError:列表索引超出范围“list = self.scanFolder(path [t])”

这是一个Object,并且有一些未在此处显示的方法/函数,因为它们与此代码无关。

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 个答案:

答案 0 :(得分:1)

您正在尝试访问无效位置。

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

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

您应该以更加pythonic的形式访问列表元素:

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

如果您需要更改某些列表元素,则应使用enumerate()

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