【发布时间】:2014-11-15 08:22:09
【问题描述】:
我正在编写一个简单的 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])
【问题讨论】:
-
哪一行出现超出范围错误?
-
@Crummy:看起来他们得到错误的可能行是倒数第二行 - 它是唯一具有非切片列表索引的行。该问题可能与输入一个不在 1 ... processFile.counter 范围内的数字以响应输入提示有关。
-
list是Python中的保留字,你当然可以用它作为变量名,但是你屏蔽了内置的使用 -
请阅读stackoverflow.com/help/mcve并提供完整的回溯。
-
是的,即使输入为 2,我也会在代码的倒数第二行得到错误
标签: python list python-2.7 outofrangeexception