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

来源:互联网 发布:网络爬虫爬取什么赚钱 编辑:程序博客网 时间:2024/06/01 07:44

切割文件的合并

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

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

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

#!/usr/bin/env pythonimport osimport sysdef 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