7.python学习笔记:切割文件的合并

切割文件的合并

在上一篇文章中介绍了如何进行大型文件的切分,从而有利于文件的传输,但是在传输到指定位置之后,我们还需要把这些文件排序后进行合并,从而恢复大型文件。

合并文件的脚本需要如下参数:

fromdir 从那个目录里的文件进行合并
tofile 合并后的大文件名称

#!/usr/bin/env python

import os
import sys

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(readsize)
            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 ('Use: join.py [from-dir-name to-file-name]')
    else :
        if len(sys.argv) != 3 :
            interactive = True
            fromdir = raw_input('Directory containing part file:')
            tofile = raw_input('Name of file to be reaceated:')
        else :
            interactive = False
            fromdir, tofile = sys.argv[1:3]
        absfrom, absto = map(os.path.abspath, [fromdir, tofile])
        print ('Joining ', absfrom, ' to make ', absto)

        try:
            join(fromdir, tofile)
        except:
            print ('Error joining files:')
            print (sys.exc_info()[0], sys.exe_info()[1])
        else:
            print ('Join complate: see', absto)
        if interactive:
            input('Press Enter key.')

小结:

学习python需要点滴的积累,遇到巧妙的方法需要赶紧记录起来,滴水石穿,最终一定会产生质变。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值