Search code examples
pythonvideo-processingmoviepy

Moviepy - Create multiple subclips using times from CSV file


I am creating a Python script which uses the MoviePy module, to take clips from a larger video and concatenate them together.

The times for the clips are detailed in a CSV file like so;

0,10

11,19

15,20

34,42 etc

What I have done is read the CSV file row by row and then using the subclip method from Moviepy created a clip which is stored in a list of clips, however I get a IndexError - list index out of range.

What could be the issue (the code works fine if I don't use the subclip method with the values from the CSV file)?

This is my code:

video= VideoFileClip('file')

clipsArray = [] 

import csv
with open('csv file', 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        startTime = row[0]
        endTime = row[1]
        clip = fullVideo.subclip(startTime, endTime)
        clipsArray.append(clip)

The error message is:

File "C:\Anaconda3\envs\py35\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 685, in runfile execfile(filename, namespace)

File "C:\Anaconda3\envs\py35\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 85, in execfile exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)

File "C:/spyder2-py3/program.py", line 32, in clip = fullVideo.subclip(start, end) # Create clips for each of the timestamps

File "", line 2, in subclip

File "C:\Anaconda3\envs\py35\lib\site-packages\moviepy\decorators.py", line 86, in wrapper for (arg, name) in zip(a, names)]

File "C:\Anaconda3\envs\py35\lib\site-packages\moviepy\decorators.py", line 86, in for (arg, name) in zip(a, names)]

File "C:\Anaconda3\envs\py35\lib\site-packages\moviepy\tools.py", line 78, in cvsecs finds = re.findall(expr, time)[0]

IndexError: list index out of range

CSV file:

0,12 16,21 22,29 34,59 89,130 140,160 162,171


Solution

  • The reason it failed is because when you read from this csv file you get startTime and endTime as strings, for instance '0' and '12' in the first line.

    MoviePy only accepts two formats for times:

    • A numeric format (int or float) representing the number of seconds
    • A string of the form 'hh:mm:ss.dd' (hours, minutes, seconds, decimals of seconds), e.g. '05:12:10.50' for 5 hours 12 minutes and 10.5 seconds.

    So you should write

    startTime = float(row[0])
    endTime = float(row[1])
    clip = fullVideo.subclip(startTime, endTime)