python实现大文件分割与合并

yipeiwu_com6年前Python基础

很多时候我们会面临大文件无法加载到内存,或者要传输大文件的问题。这时候就需要考虑将大文件分割为小文件进行处理了。

下面是一种用python分割与合并分件的实现。

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):
  '''
  文件按照数据块大小分割为多个子文件
  INPUT -> 文件目录, 文件名, 每个数据块大小
  '''
  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):
  '''
  文件按照行分割成多个子文件
  INPUT -> 文件目录, 文件名, 行数
  '''
  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()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python使用rsa非对称加密过程解析

python使用rsa非对称加密过程解析

这篇文章主要介绍了python使用rsa非对称加密过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1、安装rsa 支持pyth...

python numpy 矩阵堆叠实例

在实际操作中,遇到了矩阵堆叠的操作,本来想着自己写一个函数,后来想,应该有库函数,于是一阵找寻 import numpy as np a = np.array([1,2,3]) b...

Python Dataframe 指定多列去重、求差集的方法

1)去重 指定多列去重,这是在dataframe没有独一无二的字段作为PK(主键)时,需要指定多个字段一起作为该行的PK,在这种情况下对整体数据进行去重。 Attention:主要用到了...

pytorch 自定义卷积核进行卷积操作方式

pytorch 自定义卷积核进行卷积操作方式

一 卷积操作:在pytorch搭建起网络时,大家通常都使用已有的框架进行训练,在网络中使用最多就是卷积操作,最熟悉不过的就是 torch.nn.Conv2d(in_channels,...

详解Python字符串对象的实现

详解Python字符串对象的实现

PyStringObject 结构体 Python 中的字符串对象在内部对应一个名叫 PyStringObject 的结构体。“ob_shash” 对应字符串经计算过的 hash值, “...