List out of range error in python code

624 views Asked by At

I am writing a simple python program which allows us to list all video files in a directory and play them according to the user input. However, I am getting an list out of range error while running this code.

Code:

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

There are 1 answers

1
Cel Skeggs On

Aha, found your problem.

In processFile, you say

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

This means that, whenever you recurse, you are clearing the list again! This means that the processFile.counter number becomes out-of-sync with the actual length of list.

Three notes on this:

  • Storing variables on a function like processFile.counter is generally frowned upon, AFAIK.
  • There's no need for a separate counter; you can simply put len(list) to find the number of entries in your list.
  • To fix the list problem itself, consider initializing the list variable outside of the function or passing it in as a parameter to be modified.