divide a disk image into smaller parts using Python
<p>I would like to write a program that takes a .dmg file that is 1.6 GB and split it into 100 MB chunks.</p>

<p>I would like to also write another program that later can put everything back together so that it can be mounted and used.</p>

<p>I am very new to Python (and any type of programming language in general) and cannot find anything on here about this specific thing. Let me know if I am using incorrect terminology too so that I can learn how to search more effectively. </p>

<p>Thanks!</p>

<p>Try this example:</p>

<p><strong>split.py</strong></p>

<pre><code>import sys, os
kilobytes = 1024
megabytes = kilobytes * 1000
chunksize = int(1.4 * megabytes)                   

def split(fromfile, todir, chunksize=chunksize):
    if not os.path.exists(todir):
        os.mkdir(todir)
    else:
        for fname in os.listdir(todir):
            os.remove(os.path.join(todir, fname))
    partnum = 0
    input = open(fromfile, 'rb')
    while 1:
        chunk = input.read(chunksize)
        if not chunk: break
        partnum  = partnum+1
        filename = os.path.join(todir, ('part%04d' % partnum))
        fileobj  = open(filename, 'wb')
        fileobj.write(chunk)
        fileobj.close()
    input.close(  )
    assert partnum &lt;= 9999
    return partnum

if __name__ == '__main__':
    try:
        parts = split('/Users/example/Desktop/SO/st/example.mp4', '/Users/example/Desktop/SO/st/new', 2000000) # 100000000 == 100 mb
    except:
        print('Error during split')
</code></pre>

<p>for join:</p>

<p><strong>join.py</strong></p>

<pre><code>import os, sys
readsize = 1024

def join(fromdir, tofile):
    output = open(tofile, 'wb')
    parts  = os.listdir(fromdir)
    parts.sort(  )
    for filename in parts:
        filepath = os.path.join(fromdir, filename)
        fileobj  = open(filepath, 'rb')
        while 1:
            filebytes = fileobj.read(readsize)
            if not filebytes: break
            output.write(filebytes)
        fileobj.close(  )
    output.close(  )

if __name__ == '__main__':
    try:
        join('/Users/example/Desktop/SO/st/new', 'example_join.mp4')
    except:
        print('Error joining files:')
    else:
       print('Join complete!')
</code></pre>

python python-3.x dmg