python實(shí)現(xiàn)文件的分割與合并
使用Python來(lái)進(jìn)行文件的分割與合并是非常簡(jiǎn)單的。
python代碼如下:
splitFile--將文件分割成大小為chunksize的塊;
mergeFile--將眾多文件塊合并成原來(lái)的文件;
# 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 讀二進(jìn)制文件
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路徑下的所有文件塊合并,并存儲(chǔ)到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報(bào)告作業(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()
程序注釋部分是使用類的對(duì)象的方法。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python開(kāi)發(fā)簡(jiǎn)易版在線音樂(lè)播放器
這篇文章主要為大家詳細(xì)介紹了python開(kāi)發(fā)簡(jiǎn)易版在線音樂(lè)播放器的相關(guān)資料,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-03-03
Ubuntu 20.04安裝Pycharm2020.2及鎖定到任務(wù)欄的問(wèn)題(小白級(jí)操作)
這篇文章主要介紹了Ubuntu 20.04安裝Pycharm2020.2及鎖定到任務(wù)欄的問(wèn)題,本教程給大家講解的很詳細(xì),非常適合小白級(jí)操作,需要的朋友可以參考下2020-10-10
使用Python腳本對(duì)GiteePages進(jìn)行一鍵部署的使用說(shuō)明
剛好之前有了解過(guò)python的自動(dòng)化,就想著自動(dòng)化腳本,百度一搜還真有類似的文章。今天就給大家分享下使用Python腳本對(duì)GiteePages進(jìn)行一鍵部署的使用說(shuō)明,感興趣的朋友一起看看吧2021-05-05
解決django后臺(tái)管理界面添加中文內(nèi)容亂碼問(wèn)題
今天小編就為大家分享一篇解決django后臺(tái)管理界面添加中文內(nèi)容亂碼問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-11-11
YOLOv5目標(biāo)檢測(cè)之a(chǎn)nchor設(shè)定
在訓(xùn)練yolo網(wǎng)絡(luò)檢測(cè)目標(biāo)時(shí),需要根據(jù)待檢測(cè)目標(biāo)的位置大小分布情況對(duì)anchor進(jìn)行調(diào)整,使其檢測(cè)效果盡可能提高,下面這篇文章主要給大家介紹了關(guān)于YOLOv5目標(biāo)檢測(cè)之a(chǎn)nchor設(shè)定的相關(guān)資料,需要的朋友可以參考下2022-05-05
使用pyecharts1.7進(jìn)行簡(jiǎn)單的可視化大全
這篇文章主要介紹了使用pyecharts1.7進(jìn)行簡(jiǎn)單的可視化大全,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05
基python實(shí)現(xiàn)多線程網(wǎng)頁(yè)爬蟲
python是支持多線程的, 主要是通過(guò)thread和threading這兩個(gè)模塊來(lái)實(shí)現(xiàn)的,本文主要給大家分享python實(shí)現(xiàn)多線程網(wǎng)頁(yè)爬蟲,需要的朋友可以參考下2015-09-09

