python实现文件的分割与合并
程序员文章站
2023-11-30 09:36:46
使用python来进行文件的分割与合并是非常简单的。
python代码如下:
splitfile--将文件分割成大小为chunksize的块;
mergefile--...
使用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 error\n" 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:\users\justyoung\desktop\unix报告作业.docx".decode('utf-8') #test = fileoperationbase(a, "c:\users\justyoung\desktop\splitfile\est", 1024) #test.splitfile() #a = "c:\users\justyoung\desktop\splitfile\est" #test = fileoperationbase(a, "out") #test.mergefile()
程序注释部分是使用类的对象的方法。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。