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实现方法
Nov 18 Python
Python常用的爬虫技巧总结
Mar 28 Python
Flask框架的学习指南之制作简单blog系统
Nov 20 Python
Python3中类、模块、错误与异常、文件的简易教程
Nov 20 Python
Python实现将Excel转换成为image的方法
Oct 23 Python
Python从数据库读取大量数据批量写入文件的方法
Dec 10 Python
python实现三次样条插值
Dec 17 Python
使用Python的SymPy库解决数学运算问题的方法
Mar 27 Python
pyQT5 实现窗体之间传值的示例
Jun 20 Python
iPython pylab模式启动方式
Apr 24 Python
Python填充任意颜色,不同算法时间差异分析说明
May 16 Python
Python pexpect模块及shell脚本except原理解析
Aug 03 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中防止直接访问或查看或下载config.php文件的方法
2012/07/07 PHP
phpMyAdmin安装并配置允许空密码登录
2015/07/04 PHP
laravel 实现登陆后返回登陆前的页面方法
2019/10/03 PHP
js string 转 int 注意的问题小结
2013/08/15 Javascript
JS操作JSON要领详细总结
2013/08/25 Javascript
JavaScript var声明变量背后的原理示例解析
2013/10/12 Javascript
模拟用户点击弹出新页面不会被浏览器拦截
2014/04/08 Javascript
JavaScript原生对象之String对象的属性和方法详解
2015/03/13 Javascript
jQuery实现的登录浮动框效果代码
2015/09/26 Javascript
Bootstrap滚动监听(Scrollspy)插件详解
2016/04/26 Javascript
JavaScript开发Chrome浏览器扩展程序UI的教程
2016/05/16 Javascript
javascript经典特效分享 手风琴、轮播图、图片滑动
2016/09/14 Javascript
BootStrap入门教程(一)之可视化布局
2016/09/19 Javascript
angularJS模态框$modal实例代码
2017/05/27 Javascript
JS中定位 position 的使用实例代码
2017/08/06 Javascript
Three.js实现绘制字体模型示例代码
2017/09/26 Javascript
vue组件父子间通信之综合练习(聊天室)
2017/11/07 Javascript
详解Vue调用手机相机和相册以及上传
2019/05/05 Javascript
Vue检测屏幕变化来改变不同的charts样式实例
2020/10/26 Javascript
使用优化器来提升Python程序的执行效率的教程
2015/04/02 Python
Python闭包函数定义与用法分析
2018/07/20 Python
python将秒数转化为时间格式的实例
2018/09/16 Python
Python格式化输出--%s,%d,%f的代码解析
2020/04/29 Python
Python连接Mysql进行增删改查的示例代码
2020/08/03 Python
Django通过设置CORS解决跨域问题
2020/11/26 Python
CSS3 filter(滤镜)实现网页灰色或者黑色模式的代码
2020/11/30 HTML / CSS
Reebok俄罗斯官方网上商店:购买锐步运动服装和鞋子
2016/09/26 全球购物
预订奥兰多和佛罗里达州公园门票:FloridaTix
2018/01/03 全球购物
央视元宵晚会主持串词
2014/03/25 职场文书
保研推荐信
2014/05/09 职场文书
招商引资工作汇报
2014/10/28 职场文书
教师先进事迹材料
2014/12/16 职场文书
2016年机关单位节能宣传周活动总结
2016/04/05 职场文书
2019年家电促销广告语集锦
2019/10/21 职场文书
使用PDF.js渲染canvas实现预览pdf的效果示例
2021/04/17 Javascript
python实现简单的聊天小程序
2021/07/07 Python