很多時(shí)候我們會(huì)面臨大文件無(wú)法加載到內(nèi)存,或者要傳輸大文件的問(wèn)題。這時(shí)候就需要考慮將大文件分割為小文件進(jìn)行處理了。

下面是一種用python分割與合并分件的實(shí)現(xiàn)。
import os
FILE_DIR = os.path.dirname(os.path.abspath(__file__))
#========================================================
# 文件操作
#========================================================
def get_filelist1(dir, postfix):
'''
按照后綴返回文件名列表
INPUT -> 目錄地址, 文件后綴
OUTPUT -> 文件名列表
'''
return [os.path.join(dir, f) for f in os.listdir(dir) if f.endswith(postfix)]
def get_filelist2(dir, preffix):
'''
按照前綴返回文件名列表
INPUT -> 目錄地址, 文件前綴
OUTPUT -> 文件名列表
'''
return [os.path.join(dir, f) for f in os.listdir(dir) if f.startswith(preffix)]
def get_file_postfix(filename):
'''
獲取文件名后綴
INPUT -> 文件名
OUTPUT -> 文件后綴
'''
file = os.path.splitext(filename)
preffix, postfix = file
return postfix
def get_file_preffix(filename):
'''
獲取文件名前綴
INPUT -> 文件名
OUTPUT -> 文件前綴
'''
file = os.path.splitext(filename)
preffix, postfix = file
return preffix
def file_chunkspilt(path, filename, chunksize):
'''
文件按照數(shù)據(jù)塊大小分割為多個(gè)子文件
INPUT -> 文件目錄, 文件名, 每個(gè)數(shù)據(jù)塊大小
'''
if chunksize > 0:
filepath = path+'/'+filename
partnum = 0
inputfile = open(filepath, 'rb')
while True:
chunk = inputfile.read(chunksize)
if not chunk:
break
partnum += 1
newfilename = os.path.join(path, (filename+'_%04d' % partnum))
sub_file = open(newfilename, 'wb')
sub_file.write(chunk)
sub_file.close()
inputfile.close()
else:
print('chunksize must bigger than 0!')
def file_linespilt(path, filename, limit):
'''
文件按照行分割成多個(gè)子文件
INPUT -> 文件目錄, 文件名, 行數(shù)
'''
if limit > 0:
preffix = get_file_preffix(filename)
postfix = get_file_postfix(filename)
file_count = 0
l_list = []
with open(path+'/'+filename, 'rb') as f:
for line in f:
l_list.append(line)
if len(l_list) < limit:
continue
subfile = preffix+"_"+str(file_count)+"."+postfix
with open(FILE_DIR+'/'+subfile, 'wb') as file:
for l in l_list[:-1]:
file.write(l)
file.write(l_list[-1].strip())
l_list=[]
file_count += 1
else:
print('limit must bigger than 0!')
def file_combine(path, filename):
'''
子文件合并
INPUT -> 文件目錄, 文件名
'''
filepath = path+'/'+filename
partnum = 0
outputfile = open(filepath, 'wb')
subfile_list = get_filelist2(FILE_DIR, filename+'_')
for subfile in subfile_list:
temp = open(subfile, 'rb')
outputfile.write(temp.read())
temp.close()
outputfile.close()
標(biāo)題名稱:python實(shí)現(xiàn)大文件分割與合并-創(chuàng)新互聯(lián)
鏈接分享:http://www.chinadenli.net/article44/ccpoee.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供ChatGPT、虛擬主機(jī)、企業(yè)網(wǎng)站制作、手機(jī)網(wǎng)站建設(shè)、微信小程序、電子商務(wù)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容