python 文件拆分与合并

文件拆分与合并

有的时候,存储和传输对文件的大小有约束,这个时候就可以使用文件拆分与合并

import glob
import sys

# chunk_size的单位是byte
def split_file(file_path, chunk_size):
    with open(file_path, 'rb') as f:
        index = 0
        while True:
            if index > 100:
                print('Too many part!')
                sys.exit()                      # 避免产生的文件太多,最后导致文件夹都打不开
            chunk_data = f.read(chunk_size)
            print(index)
            if not chunk_data:
                break
            with open(file_path + '.part' + str(index), 'wb') as chunk_file:
                chunk_file.write(chunk_data)
                index += 1


def merge_file(output_file_path, input_file_prefix):
    with open(output_file_path, 'wb') as out_file:
        input_file_paths = glob.glob(input_file_prefix + '.part*')
        print(input_file_paths)
        for input_file_path in input_file_paths:
            with open(input_file_path, 'rb') as in_file:
                out_file.write(in_file.read())


def main():
    # split_file(r'C:\\Users\\USER\Downloads\\pycharm-community-2023.2.3.exe', 100000000)
    merge_file(r'C:\\Users\\USER\Downloads\\a.exe', 'C:\\Users\\USER\Downloads\\pycharm-community-2023.2.3.exe')


if __name__ == '__main__':
    main()
posted @ 2023-10-20 11:07  下夕阳  阅读(77)  评论(0编辑  收藏  举报