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进阶教程之循环对象

这一讲的主要目的是为了大家在读Python程序的时候对循环对象有一个基本概念。 循环对象的并不是随着Python的诞生就存在的,但它的发展迅速,特别是Python 3x的时代,循环对象正...

Python实现TCP协议下的端口映射功能的脚本程序示例

Python实现TCP协议下的端口映射功能的脚本程序示例

1 端口映射 举个例子来说明一下端口映射的作用。 有A、B、C三台计算机,A、B互通,B、C互通,但是A、C不通,这个时候在C上开了一个Web服务,如何让A访问C的Web服务? 最简单有...

Python使用matplotlib绘制正弦和余弦曲线的方法示例

Python使用matplotlib绘制正弦和余弦曲线的方法示例

本文实例讲述了Python使用matplotlib绘制正弦和余弦曲线的方法。分享给大家供大家参考,具体如下: 一 介绍 关键词:绘图库 官网:http://matplotlib.org/...

Django Sitemap 站点地图的实现方法

Django 中自带了 sitemap框架,用来生成 xml 文件 Sitemap(站点地图)是通知搜索引擎页面的地址,页面的重要性,帮助站点得到比较好的收录。 白话文就是:一个写了你...

python tornado使用流生成图片的例子

监控中,通常要使用图片更直观的看出集群的运行状况。 以下是一个简单的demo,通过rrdtool生成动态的图片。Python3, tornado. web.py templates/in...