使用Python将磁盘映像分成更小的部分

2024-04-19 09:28:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个程序,需要一个.dmg文件,是1.6 GB和分裂成100兆块。你知道吗

我还想写另一个程序,以后可以把一切重新组合起来,以便它可以挂载和使用。你知道吗

我对Python(以及任何类型的编程语言)非常陌生,在这里找不到关于这个特定事物的任何信息。如果我使用了不正确的术语,请告诉我,这样我可以学习如何更有效地搜索。你知道吗

谢谢!你知道吗


Tags: 文件程序信息类型编程语言事物术语gb
1条回答
网友
1楼 · 发布于 2024-04-19 09:28:06

请尝试以下示例:

拆分.py

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 <= 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')

对于联接:

加入.py

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!')

相关问题 更多 >