python實現檔案的分割與合併
阿新 • • 發佈:2020-01-09
使用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()
程式註釋部分是使用類的物件的方法。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。