列出python代码中的超出范围错误

时间:2014-11-15 08:22:10

标签: python list python-2.7 outofrangeexception

我正在编写一个简单的python程序,它允许我们列出目录中的所有视频文件,并根据用户输入播放它们。但是,我在运行此代码时得到一个超出范围错误的列表。

代码:

import os

from subprocess import Popen

def processFile(currentDir):
    # Get the absolute path of the currentDir parameter
    currentDir = os.path.abspath(currentDir)                                         
    global list
    list=[]

    filesInCurDir = os.listdir(currentDir)

    # Traverse through all files
    for file in filesInCurDir:
        curFile = os.path.join(currentDir, file)

        # Check if it's a normal file or directory
        if os.path.isfile(curFile):
            # Get the file extension
            curFileExtension = curFile[-3:]

            # Check if the file has an extension of typical video files
            if curFileExtension in ['avi', 'dat', 'mp4', 'mkv', 'vob']:
                # We have got a video file! Increment the counter
                processFile.counter += 1
                list.append('curFile')

                # Print it's name
                print(processFile.counter,  file)
        else:
            # We got a directory, enter into it for further processing
            processFile(curFile)
if __name__ == '__main__':
    # Get the current working directory
    currentDir = os.getcwd()

    print('Starting processing in %s' % currentDir)

    # Set the number of processed files equal to zero
    processFile.counter = 0

    # Start Processing
    processFile(currentDir)

    # We are done. Exit now.
    print('\n -- %s Movie File(s) found in directory %s --' \
          % (processFile.counter, currentDir))
    print('Enter the file you want to play')
    x = int(input())
    path = list[x-1]
    oxmp=Popen(['omxplayer',path])

1 个答案:

答案 0 :(得分:1)

啊,啊,找到了你的问题。

processFile中,您说

def processFile(currentDir):
    # ...
    global list
    list=[]
    # ...
    processFile(...)

这意味着,无论何时递归,您都要再次清除列表!这意味着processFile.counter号码与列表的实际长度不同步。

关于此的三点说明:

  • 将变量存储在像processFile.counter这样的函数上通常不赞成,AFAIK。
  • 不需要单独的柜台;您只需添加len(list)即可找到列表中的条目数。
  • 要修复列表问题本身,请考虑在函数外部初始化列表变量,或将其作为要修改的参数传递。