python實現(xiàn)文件的分割與合并
使用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報告作業(yè).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()
程序注釋部分是使用類的對象的方法。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Pycharm使用Database?Navigator連接mysql數(shù)據(jù)庫全過程
這篇文章主要介紹了Pycharm使用Database?Navigator連接mysql數(shù)據(jù)庫全過程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07python數(shù)組復(fù)制拷貝的實現(xiàn)方法
這篇文章主要介紹了python數(shù)組復(fù)制拷貝的實現(xiàn)方法,實例分析了Python數(shù)組傳地址與傳值兩種復(fù)制拷貝的使用技巧,需要的朋友可以參考下2015-06-06Python實現(xiàn)GUI學(xué)生信息管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了Python實現(xiàn)GUI學(xué)生信息管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-01-01Python環(huán)境的安裝以及PyCharm編輯器配置教程詳解
優(yōu)質(zhì)的教程可以讓我們少走很多彎路,這一點毋庸置疑。這篇文章主要為大家介紹了純凈Python環(huán)境的安裝以及PyCharm編輯器的配置,需要的可以參考一下2023-04-04Python實現(xiàn)mysql數(shù)據(jù)庫中的SQL文件生成和導(dǎo)入
這篇文章主要介紹了Python實現(xiàn)mysql數(shù)據(jù)庫中的SQL文件生成和導(dǎo)入,首先通過將mysql數(shù)據(jù)導(dǎo)出到SQL文件中展開詳細(xì)內(nèi)容需要的小伙伴可以參考一下2022-06-06