Python实现分割文件及合并文件的方法


Posted in Python onJuly 10, 2015

本文实例讲述了Python实现分割文件及合并文件的方法。分享给大家供大家参考。具体如下:

分割文件split.py如下:

#!/usr/bin/python
##########################################################################
# split a file into a set of parts; join.py puts them back together;
# this is a customizable version of the standard unix split command-line 
# utility; because it is written in Python, it also works on Windows and
# can be easily modified; because it exports a function, its logic can 
# also be imported and reused in other applications;
##########################################################################
import sys, os
kilobytes = 1024
megabytes = kilobytes * 1000
chunksize = int(1.4 * megabytes)     # default: roughly a floppy
def split(fromfile, todir, chunksize=chunksize): 
 if not os.path.exists(todir):     # caller handles errors
  os.mkdir(todir)       # make dir, read/write parts
 else:
  for fname in os.listdir(todir):   # delete any existing files
   os.remove(os.path.join(todir, fname)) 
 partnum = 0
 input = open(fromfile, 'rb')     # use binary mode on Windows
 while 1:          # eof=empty string from read
  chunk = input.read(chunksize)    # get next part <= chunksize
  if not chunk: break
  partnum = partnum+1
  filename = os.path.join(todir, ('part%04d' % partnum))
  fileobj = open(filename, 'wb')
  fileobj.write(chunk)
  fileobj.close()       # or simply open().write()
 input.close()
 assert partnum <= 9999       # join sort fails if 5 digits
 return partnum
if __name__ == '__main__':
 if len(sys.argv) == 2 and sys.argv[1] == '-help':
  print 'Use: split.py [file-to-split target-dir [chunksize]]'
 else:
  if len(sys.argv) < 3:
   interactive = 1
   fromfile = raw_input('File to be split? ')  # input if clicked 
   todir = raw_input('Directory to store part files? ')
  else:
   interactive = 0
   fromfile, todir = sys.argv[1:3]     # args in cmdline
   if len(sys.argv) == 4: chunksize = int(sys.argv[3])
  absfrom, absto = map(os.path.abspath, [fromfile, todir])
  print 'Splitting', absfrom, 'to', absto, 'by', chunksize
  try:
   parts = split(fromfile, todir, chunksize)
  except:
   print 'Error during split:'
   print sys.exc_info()[0], sys.exc_info()[1]
  else:
   print 'Split finished:', parts, 'parts are in', absto
  if interactive: raw_input('Press Enter key') # pause if clicked

合并文件join_file.py如下:

#!/usr/bin/python
##########################################################################
# join all part files in a dir created by split.py, to recreate file. 
# This is roughly like a 'cat fromdir/* > tofile' command on unix, but is 
# more portable and configurable, and exports the join operation as a 
# reusable function. Relies on sort order of file names: must be same 
# length. Could extend split/join to popup Tkinter file selectors.
##########################################################################
import os, sys
readsize = 1024
def join(fromdir, tofile):
 output = open(tofile, 'wb')
 parts = os.listdir(fromdir)
 parts.sort()
 for filename in parts:
  filepath = os.path.join(fromdir, filename)
  fileobj = open(filepath, 'rb')
  while 1:
   filebytes = fileobj.read(readsize)
   if not filebytes: break
   output.write(filebytes)
  fileobj.close()
 output.close()
if __name__ == '__main__':
 if len(sys.argv) == 2 and sys.argv[1] == '-help':
  print 'Use: join.py [from-dir-name to-file-name]'
 else:
  if len(sys.argv) != 3:
   interactive = 1
   fromdir = raw_input('Directory containing part files? ')
   tofile = raw_input('Name of file to be recreated? ')
  else:
   interactive = 0
   fromdir, tofile = sys.argv[1:]
  absfrom, absto = map(os.path.abspath, [fromdir, tofile])
  print 'Joining', absfrom, 'to make', absto
  try:
   join(fromdir, tofile)
  except:
   print 'Error joining files:'
   print sys.exc_info()[0], sys.exc_info()[1]
  else:
   print 'Join complete: see', absto
  if interactive: raw_input('Press Enter key') # pause if clicked

希望本文所述对大家的Python程序设计有所帮助。

Python 相关文章推荐
python实现将元祖转换成数组的方法
May 04 Python
详解Python list 与 NumPy.ndarry 切片之间的对比
Jul 24 Python
python下载文件记录黑名单的实现代码
Oct 24 Python
python实现装饰器、描述符
Feb 28 Python
Python3.5 创建文件的简单实例
Apr 26 Python
Win10下python3.5和python2.7环境变量配置教程
Sep 18 Python
Python音频操作工具PyAudio上手教程详解
Jun 26 Python
如何在Python 游戏中模拟引力
Mar 27 Python
python利用os模块编写文件复制功能——copy()函数用法
Jul 13 Python
Matplotlib 折线图plot()所有用法详解
Jul 28 Python
利用python 读写csv文件
Sep 10 Python
Python实现双向链表基本操作
May 25 Python
Python写入数据到MP3文件中的方法
Jul 10 #Python
Python将阿拉伯数字转换为罗马数字的方法
Jul 10 #Python
Python自动登录126邮箱的方法
Jul 10 #Python
Python获取邮件地址的方法
Jul 10 #Python
python实现中文分词FMM算法实例
Jul 10 #Python
Python实现的最近最少使用算法
Jul 10 #Python
Python导入oracle数据的方法
Jul 10 #Python
You might like
php 3行代码的分页算法(求起始页和结束页)
2009/10/21 PHP
php 静态变量的初始化
2009/11/15 PHP
PHP版本如何选择?应该使用哪个版本?
2015/05/13 PHP
php中mkdir()函数的权限问题分析
2016/09/24 PHP
php 5.4 全新的代码复用Trait详解
2017/01/05 PHP
总结的一些PHP开发中的tips(必看篇)
2017/03/24 PHP
thinkPHP利用ajax异步上传图片并显示、删除的示例
2018/09/26 PHP
javascript attachEvent绑定多个事件执行顺序问题
2010/10/20 Javascript
使用jquery与图片美化checkbox和radio控件的代码(打包下载)
2010/11/11 Javascript
JS函数实现动态添加CSS样式表文件
2012/12/15 Javascript
js/jQuery简单实现选项卡功能
2014/01/02 Javascript
简介JavaScript中的setHours()方法的使用
2015/06/11 Javascript
jquery用ajax方式从后台获取json数据后如何将内容填充到下拉列表
2015/08/26 Javascript
php利用curl获取远程图片实现方法
2015/10/26 Javascript
JavaScript 弹出子窗体并返回结果到父窗体的实现代码
2016/05/28 Javascript
使用 NodeJS+Express 开发服务端的简单介绍
2017/04/07 NodeJs
JavaScript数组排序reverse()和sort()方法详解
2017/12/24 Javascript
使用vue的transition完成滑动过渡的示例代码
2018/06/25 Javascript
Vue数据双向绑定的深入探究
2018/11/27 Javascript
浅谈Javascript中的对象和继承
2019/04/19 Javascript
layui的select联动实现代码
2019/09/28 Javascript
mpvue实现左侧导航与右侧内容的联动
2019/10/21 Javascript
Vue实现数据请求拦截
2019/10/23 Javascript
vue路由拦截器和请求拦截器知识点总结
2019/11/08 Javascript
jquery实现垂直手风琴导航栏
2020/02/18 jQuery
ES5新增数组的实现方法
2020/05/12 Javascript
python简单获取本机计算机名和IP地址的方法
2015/06/03 Python
解决.ui文件生成的.py文件运行不出现界面的方法
2019/06/19 Python
python tornado使用流生成图片的例子
2019/11/18 Python
Python 开发工具PyCharm安装教程图文详解(新手必看)
2020/02/28 Python
htmlentities() 和 htmlspecialchars()有什么区别
2015/07/01 面试题
测控技术与仪器个人求职信范文
2013/12/30 职场文书
2015年八一建军节慰问信
2015/03/23 职场文书
三严三实·严以律己心得体会
2016/01/13 职场文书
详解nginx location指令
2022/01/18 Servers
浅谈Vue的computed计算属性
2022/03/21 Vue.js