美文网首页
Python 把切割的文件合并为一个文件。

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

作者: 喵呜e喵星人 | 来源:发表于2020-08-27 21:38 被阅读0次
'''
合并文件
找到要合并的文件目录,对文件夹内的所有文件先进行排序,再使用二进制的方式写入到一个文件中。



'''

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("请按任意键结束运行!")

相关文章

网友评论

      本文标题:Python 把切割的文件合并为一个文件。

      本文链接:https://www.haomeiwen.com/subject/tsbhsktx.html