use python to split a video file into a set of parts

iMath redstone-cold at 163.com
Tue May 7 07:15:38 EDT 2013


I use the following python code to split a FLV video file into a set of parts ,when finished ,only the first part video can be played ,the other parts are corrupted.I wonder why and Is there some correct ways to split video files

import sys, os
kilobytes = 1024
megabytes = kilobytes * 1000
chunksize = int(1.4 * megabytes)                   # default: roughly a floppy

print(chunksize , type(chunksize ))

def split(fromfile, todir, chunksize=chunksize):
    if not os.path.exists(todir):                  # caller handles errors
        os.mkdir(todir)                            # make dir, read/write parts
    else:
        for fname in os.listdir(todir):            # delete any existing files
            os.remove(os.path.join(todir, fname))
    partnum = 0
    input = open(fromfile, 'rb')                   # use binary mode on Windows
    while True:                                    # eof=empty string from read
        chunk = input.read(chunksize)              # get next part <= chunksize
        if not chunk: break
        partnum += 1
        filename = os.path.join(todir, ('part{}.flv'.format(partnum)))
        fileobj  = open(filename, 'wb')
        fileobj.write(chunk)
        fileobj.close()                            # or simply open().write()
    input.close()
    assert partnum <= 9999                         # join sort fails if 5 digits
    return partnum

if __name__ == '__main__':

    fromfile = input('File to be split: ')           # input if clicked
    todir    = input('Directory to store part files:')
    print('Splitting', fromfile, 'to', todir, 'by', chunksize)
    parts = split(fromfile, todir, chunksize)
    print('Split finished:', parts, 'parts are in', todir)



More information about the Python-list mailing list