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])
Aha, found your problem.
In
processFile
, you sayThis 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:
processFile.counter
is generally frowned upon, AFAIK.len(list)
to find the number of entries in your list.