溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python如何實現(xiàn)文件的分割與合并

發(fā)布時間:2021-04-06 10:49:48 來源:億速云 閱讀:196 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要介紹python如何實現(xiàn)文件的分割與合并,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

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()

程序注釋部分是使用類的對象的方法。

以上是“python如何實現(xiàn)文件的分割與合并”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI