Auto-splitting video file in equal chunks with ffmpeg and python

UPDATE: The source code for this simple script has been moved to GitHub, get it here:

Recently I needed to upload a whole bunch of long video files. Maximum allowed length for each video was just few minutes, while the actual length of files I tried to upload were about an hour each. FFmpeg is really great for splitting the video files and Python is quite handy for automating the task. Combining two together in this handy little script(see below). The script below takes a video file and a chunk size in seconds and splits the video file into chunks using ffmpeg, so each chunk is self contained, playable video.

Source code:

#!/usr/bin/env python

import subprocess
import re
import math
from optparse import OptionParser

length_regexp = 'Duration: (\d{2}):(\d{2}):(\d{2})\.\d+,'
re_length = re.compile(length_regexp)

def main():

    (filename, split_length) = parse_options()
    if split_length <= 0:
        print "Split length can't be 0"
        raise SystemExit

    output = subprocess.Popen("ffmpeg -i '"+filename+"' 2>&1 | grep 'Duration'", 
                            shell = True,
                            stdout = subprocess.PIPE
    print output
    matches =
    if matches:
        video_length = int( * 3600 + \
                        int( * 60 + \
        print "Video length in seconds: "+str(video_length)
        print "Can't determine video length."
        raise SystemExit

    split_count = math.ceil(video_length/float(split_length))
    if(split_count == 1):
        print "Video length is less then the target split length."
        raise SystemExit

    split_cmd = "ffmpeg -i '"+filename+"' -vcodec copy "
    for n in range(0, split_count):
        split_str = ""
        if n == 0:
            split_start = 0
            split_start = split_length * n
        split_str += " -ss "+str(split_start)+" -t "+str(split_length) + \
                    " '"+filename[:-4] + "-" + str(n) + "." + filename[-3:] + \
        print "About to run: "+split_cmd+split_str
        output = subprocess.Popen(split_cmd+split_str, shell = True, stdout =

def parse_options():
    parser = OptionParser()    
    parser.add_option("-f", "--file",
                        dest = "filename",
                        help = "file to split, for example sample.avi",
                        type = "string",
                        action = "store"
    parser.add_option("-s", "--split-size",
                        dest = "split_size",
                        help = "split or chunk size in seconds, for example 10",
                        type = "int",
                        action = "store"
    (options, args) = parser.parse_args()
    if options.filename and options.split_size:

        return (options.filename, options.split_size)

        raise SystemExit

if __name__ == '__main__':

    except Exception, e:
        print "Exception occured running main():"
        print str(e)

Or download it here: splitting video file script link

16 thoughts on “Auto-splitting video file in equal chunks with ffmpeg and python

  1. Hi there,

    I found this blog entry to be just what i needed. I am currently trying to split a single video file into several pieces. However, after tinkering around with your script, i have a few questions that i need help with:

    1. What video files is the script meant for? I tinkered with AVI, MOV, and WMV so far, and i’m not having much luck getting mov and wmv to split and play correctly.
    2. Although my avi file does get split, i hit two problems:
    ___a. some of the split files aren’t the correct chunk size (ie. i had the split_size = 30 (seconds), yet some of the files were 60 or more
    ___b. the first split file played the video correctly, but the rest merely displayed a still image and audio continued. Know what is happening?
    3. Could you point me in the right direction to learn more about ffmpeg btw?

    Thanks again for this entry and your help in advance.


    Please let me know! And please don’t consider this spam!

  2. Hey Matt,

    Glad that you found this useful.
    In regards to your questions:
    1. This script is really just a convenience wrapper around FFmpeg, so you can use whatever formats your install of ffmpeg supports. To add support for more formats you may need to recompile ffmpeg. For mov and wmv you need to make sure you have appropriate codes. I think you need libx264 for mov. Not sure what you need to wmv. Try googling ffmpeg wmv or something like that

    2. This might be a bug… or your ffmpeg missing some libs. Can you upload your avi file to something like http// and give me a link to take a look at? Also what command line params did u use?

    3. FFmpeg docs are pretty good – but might be a bit rigid. Just google for ffmpeg commands to get a bunch of articles about various handy things you can do with it

  3. I’ve also found that splitting WMV’s does not seem to work. No matter what you specify in the -t option, it will always encode the whole video (which I believe is a bug in ffmpeg).

  4. I know this is somewhat late from when this was originally posted, but for me this script raises an invalid range() argument exception – math.ceil() returns a float (at least for me in python 2.7.1 and all 2.x.x as far as I recall). Thus line 33 should read:

    split_count = int(math.ceil(video_length/float(split_length)))

  5. The script should also set ‘-acodec copy’ so that the audio is not re-encoded when the file is split up. Just split the audio with the video.

    Also, the range error is still broken – can you update that?

  6. I put the int fix in and added -acodec copy but also changed ffmpeg instances to avconv. Worked on large mp4 videos.
    Thanks very much for the script.
    Now I can incorporate it all into a batch spilitter in bash.

  7. Pingback: Application for slicing video [duplicate] | XL-UAT

  8. Pingback: Using Python script to cut long videos into chunks in FFMPEG | 我爱源码网

  9. Pingback: Using Python script to cut long videos into chunks in FFMPEG | FYTRO SPORTS

  10. Pingback: Splitting an MP4 file | XL-UAT

  11. Pingback: What to use to quickly cut Audio/Video - Popular Ubuntu Questions

  12. Learn how to write an assessment literature.
    Подробнее читайте здесь
    - обзор
    What is evaluation literature?
    Writing the introduction
    Writing your body
    Writing concluding
    What is overview of literature?
    The format of an assessment of literature can vary from discipline to discipline and from assignment to assignment.

    A review might be a self-contained unit — a finish in itself — or
    maybe a preface to and rationale for doing primary research.
    A review is usually a required component of grant and research proposals
    and quite often a chapter in theses and dissertations.

    Generally, the purpose of the review should be to analyze critically
    a segment of any published body of information through summary, classification, and comparison of prior scientific
    tests, reviews of literature, and theoretical articles.

    Writing the introduction
    In the introduction, you ought to:

    Define or identify the overall topic, issue, or region of concern, thus providing a
    proper context for reviewing the literature.
    Point out overall trends with what has been published about the subject; or conflicts
    theoretically, methodology, evidence, and conclusions; or
    gaps in research and scholarship; or even a single problem or new perspective of
    immediate interest.
    Establish the writer’s reason (viewpoint) for reviewing the literature; explain the factors to
    be used in analyzing and comparing literature plus the organization with the review (sequence); and, at the appropriate interval, state why certain literature is or possibly is not included (scope).


    Writing our bodies
    In your body, you ought to:

    Group clinical tests and other forms of literature (reviews, theoretical articles,
    case studies, etc.) in line with common denominators for instance qualitative versus quantitative approaches, conclusions
    of authors, specific purpose or objective, chronology,
    Summarize individual studies or articles with all the
    or very little detail as each merits based on its comparative importance within the literature, remembering
    that space (length) denotes significance.
    Provide people with strong “umbrella” sentences at beginnings of paragraphs, “signposts” throughout,
    and brief “so what” summary sentences at intermediate points inside review to assistance with understanding comparisons and analyses.

    Writing the actual final outcome
    In in conclusion, you must:

    Summarize major contributions of significant
    studies and articles for the body of info under review, maintaining the main focus established
    within the introduction.
    Evaluate the latest “state in the art” with the body of information reviewed, declaring major
    methodological flaws or gaps in research, inconsistencies in principle and findings,
    and areas or issues pertinent to future study.
    Conclude by offering some clues about the relationship involving the
    central topic from the literature review and also a larger region of study
    for example a discipline, a scientific endeavor, or maybe a profession.

    For more info see our handouts on Writing a Critical Review of
    your Nonfiction Book or Article or Reading a Book to Review It.

    To read more about literature reviews, examine our workshop on Writing Literature Reviews of Published Research.

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>