How to spilt a binary file into multiple files using Python?



To split a big binary file in multiple files, you should first read the file by the size of chunk you want to create, then write that chunk to a file, read the next chunk and repeat until you reach the end of original file.

Example

For example, you have a file called my_song.mp3 and want to split it in files of size 500 bytes each.

CHUNK_SIZE = 500
file_number = 1
with open('my_song.mp3') as f:
    chunk = f.read(CHUNK_SIZE)
    while chunk:
        with open('my_song_part_' + str(file_number)) as chunk_file:
            chunk_file.write(chunk)
        file_number += 1
        chunk = f.read(CHUNK_SIZE)

In your current directory, now you'll find chunks of your original file scattered across multiple files with prefix as: my_song_part_


Advertisements