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访问MySQL封装的常用类实例
Nov 11 Python
Python标准库内置函数complex介绍
Nov 25 Python
Python中解析JSON并同时进行自定义编码处理实例
Feb 08 Python
在Linux系统上部署Apache+Python+Django+MySQL环境
Dec 24 Python
Python函数中*args和**kwargs来传递变长参数的用法
Jan 26 Python
python在Windows下安装setuptools(easy_install工具)步骤详解
Jul 01 Python
python针对不定分隔符切割提取字符串的方法
Oct 26 Python
Django Rest framework之权限的实现示例
Dec 17 Python
超实用的 30 段 Python 案例
Oct 10 Python
ITK 实现多张图像转成单个nii.gz或mha文件案例
Jul 01 Python
Python如何爬取51cto数据并存入MySQL
Aug 25 Python
Elasticsearch 批量操作
Apr 19 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中通过ADO调用Access数据库的方法测试不通过
2006/12/31 PHP
关于使用coreseek并为其做分页的介绍
2013/06/21 PHP
php引用传值实例详解学习
2013/11/06 PHP
PHP中copy on write写时复制机制介绍
2014/05/13 PHP
PHP基于新浪IP库获取IP详细地址的方法
2017/05/04 PHP
PHP join()函数用法与实例讲解
2019/03/11 PHP
常用参考资料(手册)下载或者链接
2006/07/22 Javascript
ext 同步和异步示例代码
2009/09/18 Javascript
推荐40个非常优秀的jQuery插件和教程【系列三】
2011/11/09 Javascript
页面只能打开一次Cooike如何实现
2012/12/04 Javascript
js中的replace方法使用介绍
2013/10/28 Javascript
JS实现倒计时和文字滚动的效果实例
2014/10/29 Javascript
javascript实现五星评分功能
2015/11/10 Javascript
Node.js包管理器Yarn的入门介绍与安装
2016/10/17 Javascript
jQuery删除当前节点元素
2016/12/07 Javascript
浅谈js中同名函数和同名变量的执行问题
2017/02/12 Javascript
React中使用collections时key的重要性详解
2017/08/07 Javascript
vue 表单输入格式化中文输入法异常问题
2018/05/30 Javascript
vue和webpack安装命令详解
2018/06/15 Javascript
JavaScript中call和apply方法的区别实例分析
2018/08/03 Javascript
利用原生JS实现欢乐水果机小游戏
2020/04/23 Javascript
vue开发简单上传图片功能
2020/06/30 Javascript
javascript利用canvas实现鼠标拖拽功能
2020/07/23 Javascript
[43:41]OG vs Newbee 2019国际邀请赛淘汰赛 胜者组 BO3 第一场 8.21.mp4
2020/07/19 DOTA
使用python实现strcmp函数功能示例
2014/03/25 Python
python的tkinter布局之简单的聊天窗口实现方法
2014/09/03 Python
Tornado 多进程实现分析详解
2018/01/12 Python
PyQt QCombobox设置行高的方法
2019/06/20 Python
Django实现基于类的分页功能
2019/10/31 Python
webapp字号大小跟随系统字号大小缩放的示例代码
2018/12/26 HTML / CSS
美国婚礼和派对礼品网站:Kate Aspen(新娘送礼会、迎婴派对)
2018/03/28 全球购物
七一表彰活动方案
2014/01/18 职场文书
中小学生安全教育观后感
2015/06/17 职场文书
2015年董事长秘书工作总结
2015/07/23 职场文书
Python使用protobuf序列化和反序列化的实现
2021/05/19 Python
MySQL分区以及建索引的方法总结
2022/04/13 MySQL