python實現(xiàn)文件的分割與合并
更新時間:2019年08月29日 09:25:11 作者:just_young
這篇文章主要為大家詳細介紹了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)文章
Ubuntu 20.04安裝Pycharm2020.2及鎖定到任務(wù)欄的問題(小白級操作)
這篇文章主要介紹了Ubuntu 20.04安裝Pycharm2020.2及鎖定到任務(wù)欄的問題,本教程給大家講解的很詳細,非常適合小白級操作,需要的朋友可以參考下2020-10-10
使用Python腳本對GiteePages進行一鍵部署的使用說明
剛好之前有了解過python的自動化,就想著自動化腳本,百度一搜還真有類似的文章。今天就給大家分享下使用Python腳本對GiteePages進行一鍵部署的使用說明,感興趣的朋友一起看看吧2021-05-05
YOLOv5目標檢測之a(chǎn)nchor設(shè)定
在訓(xùn)練yolo網(wǎng)絡(luò)檢測目標時,需要根據(jù)待檢測目標的位置大小分布情況對anchor進行調(diào)整,使其檢測效果盡可能提高,下面這篇文章主要給大家介紹了關(guān)于YOLOv5目標檢測之a(chǎn)nchor設(shè)定的相關(guān)資料,需要的朋友可以參考下2022-05-05

