Python 把切割的文件合并为一个文件。

'''
合并文件
找到要合并的文件目录,对文件夹内的所有文件先进行排序,再使用二进制的方式写入到一个文件中。



'''

import os,sys
redsize =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 True:
            filebytes = fileobj.read(redsize)
            if not filebytes: break
            output.write(filebytes)
        fileobj.close()
    output.close()

if __name__ == "__main__":
    if len(sys.argv) == 2 and sys.argv[1] =='-help':
        print("请使用join.py  把指定的文件中切割的小文件合并为一个文件")
    else:
        if len(sys.argv) !=3:
            interactive = True
            fromdir = input("请输入要合并的目录路径")
            tofile = input("请输入要合并后的文件名及路径")
        else:
            interactive = False
            fromdir,tofile = sys.argv[1:]
    absfrom,absto = map(os.path.abspath,[fromdir,tofile])
    print("正把文件夹",absfrom,'中的文件合并到',tofile)

    try:
        join(fromdir,tofile)
    except:
        print("合并文件发送错误:")
        print(sys.exc_info()[0],sys.exc_info()[1])
    else:
        print("合并文件完成,保存的路径及文件名为:",absto)
    if interactive: input("请按任意键结束运行!")
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容