我正在编写一个简单的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])
答案 0 :(得分:1)
在processFile
中,您说
def processFile(currentDir):
# ...
global list
list=[]
# ...
processFile(...)
这意味着,无论何时递归,您都要再次清除列表!这意味着processFile.counter
号码与列表的实际长度不同步。
关于此的三点说明:
processFile.counter
这样的函数上通常不赞成,AFAIK。len(list)
即可找到列表中的条目数。