python实现文件的分割与合并

yipeiwu_com5年前Python基础

使用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报告作业.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设计】。

相关文章

python中for循环输出列表索引与对应的值方法

python中for循环输出列表索引与对应的值方法

如下所示: list = [‘a','b','c'] 想用for循环输出list的元素以及对应的索引。 代码及结果如下: 以上这篇python中for循环输出列表索引与对应的值...

python文件拆分与重组实例

python文件拆分与重组实例

文件拆分代码: #-*-encoding:utf-8-*- import os import sys import threading def getFileSi...

python字典基本操作实例分析

本文实例讲述了python字典基本操作。分享给大家供大家参考。具体如下: d2 = {'spam': 2, 'ham': 1, 'eggs': 3} # make a diction...

Python后台管理员管理前台会员信息的讲解

问题:  1. 后台管理员只有一个用户: admin, 密码: admin  2. 当管理员登陆成功后, 可以管理前台会员信息.  3. 会员信息管理包含:...

Python(TensorFlow框架)实现手写数字识别系统的方法

Python(TensorFlow框架)实现手写数字识别系统的方法

手写数字识别算法的设计与实现 本文使用python基于TensorFlow设计手写数字识别算法,并编程实现GUI界面,构建手写数字识别系统。这是本人的本科毕业论文课题,当然,这个也是机器...