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查看多台服务器进程的脚本分享
Jun 11 Python
python集合用法实例分析
May 30 Python
sublime text 3配置使用python操作方法
Jun 11 Python
对Python中TKinter模块中的Label组件实例详解
Jun 14 Python
Pandas 重塑(stack)和轴向旋转(pivot)的实现
Jul 22 Python
将自己的数据集制作成TFRecord格式教程
Feb 17 Python
Windows下实现将Pascal VOC转化为TFRecords
Feb 17 Python
python使用建议技巧分享(三)
Aug 18 Python
五分钟带你搞懂python 迭代器与生成器
Aug 30 Python
python中的插入排序的简单用法
Jan 19 Python
matplotlib之pyplot模块实现添加子图subplot的使用
Apr 25 Python
Python 用户输入和while循环的操作
May 23 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
深入解析phpCB批量转换的代码示例
2013/06/27 PHP
destoon在各个服务器下设置URL Rewrite(伪静态)的方法
2014/06/21 Servers
php实现网站顶踩功能的完整前端代码
2015/07/19 PHP
php接口实现拖拽排序功能
2018/04/23 PHP
jQuery 中关于CSS操作部分使用说明
2007/06/10 Javascript
THREE.JS入门教程(4)创建粒子系统
2013/01/24 Javascript
Struts2的s:radio标签使用及用jquery添加change事件
2013/04/08 Javascript
Jquery实现三层遍历删除功能代码
2013/04/23 Javascript
让javascript加载速度倍增的方法(解决JS加载速度慢的问题)
2014/12/12 Javascript
JavaScript中的setMilliseconds()方法使用详解
2015/06/11 Javascript
js倒计时简单实现方法
2015/12/17 Javascript
jquery正则表达式验证(手机号、身份证号、中文名称)
2015/12/31 Javascript
JS DOM实现鼠标滑动图片效果
2020/09/17 Javascript
javascript中this关键字详解
2016/12/12 Javascript
React-router v4 路由配置方法小结
2017/08/08 Javascript
vue 指定组件缓存实例详解
2018/04/01 Javascript
Vue实现双向绑定的原理以及响应式数据的方法
2018/07/02 Javascript
详解如何在微信小程序中愉快地使用sass
2018/07/30 Javascript
vue-router的钩子函数用法实例分析
2019/10/26 Javascript
js常用方法、检查是否有特殊字符串、倒序截取字符串操作完整示例
2020/01/26 Javascript
浅谈Vue使用Cascader级联选择器数据回显中的坑
2020/10/31 Javascript
[10:24]郎朗助力完美“圣”典,天籁交织奏响序曲
2016/12/18 DOTA
[04:03][TI9趣味短片] 小鸽子茶话会
2019/08/20 DOTA
Python3实现从排序数组中删除重复项算法分析
2019/04/03 Python
python异常触发及自定义异常类解析
2019/08/06 Python
基于python plotly交互式图表大全
2019/12/07 Python
Pytorch转keras的有效方法,以FlowNet为例讲解
2020/05/26 Python
鼠标滚轮事件和Mac触控板双指事件
2019/12/23 HTML / CSS
计算机应用专业学生的自我评价分享
2013/11/03 职场文书
大学生职业生涯规划范文
2013/12/31 职场文书
文明寝室申报材料
2014/05/12 职场文书
委托书格式
2014/08/01 职场文书
群众路线对照检查材料
2014/09/22 职场文书
补充协议书
2015/01/28 职场文书
闪闪红星观后感
2015/06/08 职场文书
葬礼主持词
2015/07/02 职场文书