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设计】。

相关文章

解析Python3中的Import

Python import的搜索路径 import的搜索路径为: 搜索「内置模块」(built-in module) 搜索 sys.path 中的路径 而sys.path在...

python清理子进程机制剖析

python清理子进程机制剖析

起步 在我的印象中,python的机制会自动清理已经完成任务的子进程的。通过网友的提问,还真看到了僵尸进程。 import multiprocessing as mp import...

Python3实现定时任务的四种方式

最近做一个小程序开发任务,主要负责后台部分开发;根据项目需求,需要实现三个定时任务: 1>定时更新微信token,需要2小时更新一次; 2>商品定时上线; 3>定时检测...

python通过colorama模块在控制台输出彩色文字的方法

本文实例讲述了python通过colorama模块在控制台输出彩色文字的方法。分享给大家供大家参考。具体分析如下: colorama是一个python专门用来在控制台、命令行输出彩色文字...

深入理解Python变量与常量

深入理解Python变量与常量

变量是计算机内存中的一块区域,变量可以存储规定范围内的值,而且值可以改变。基于变量的数据类型,解释器会分配指定内存,并决定什么数据可以被存储在内存中。常量是一块只读的内存区域,常量一旦被...