最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
python如何实现文件的分割与合并 python实现文件的分割与合并代码
时间:2019-08-29 编辑:袖梨 来源:一聚教程网
本篇文章小编给大家分享一下python实现文件的分割与合并代码,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
使用Python来进行文件的分割与合并是非常简单的。
python代码如下:
splitFile--将文件分割成大小为chunksize的块;
mergeFile--将众多文件块合并成原来的文件;
# coding=utf-8 import os,sys reload(sys) sys.setdefaultencoding('UTF-8') class FileOperationBase: def __init__(self,srcpath, despath, chunksize = 1024): self.chunksize = chunksize self.srcpath = srcpath self.despath = despath def splitFile(self): 'split the files into chunks, and save them into despath' if not os.path.exists(self.despath): os.mkdir(self.despath) chunknum = 0 inputfile = open(self.srcpath, 'rb') #rb 读二进制文件 try: while 1: chunk = inputfile.read(self.chunksize) if not chunk: #文件块是空的 break chunknum += 1 filename = os.path.join(self.despath, ("part--%04d" % chunknum)) fileobj = open(filename, 'wb') fileobj.write(chunk) except IOError: print "read file errorn" raise IOError finally: inputfile.close() return chunknum def mergeFile(self): '将src路径下的所有文件块合并,并存储到des路径下。' if not os.path.exists(self.srcpath): print "srcpath doesn't exists, you need a srcpath" raise IOError files = os.listdir(self.srcpath) with open(self.despath, 'wb') as output: for eachfile in files: filepath = os.path.join(self.srcpath, eachfile) with open(filepath, 'rb') as infile: data = infile.read() output.write(data) #a = "C:UsersJustYoungDesktopunix报告作业.docx".decode('utf-8') #test = FileOperationBase(a, "C:UsersJustYoungDesktopSplitFileest", 1024) #test.splitFile() #a = "C:UsersJustYoungDesktopSplitFileest" #test = FileOperationBase(a, "out") #test.mergeFile()
程序注释部分是使用类的对象的方法。
相关文章
- Golang ProtoBuf的基本语法详解 10-20
- Python识别MySQL中的冗余索引解析 10-20
- Python+Pygame绘制小球代码展示 10-18
- Python中的数据精度问题介绍 10-18
- Python随机值生成的常用方法介绍 10-18
- python3解压缩.gz文件分析 09-27