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中用keys()方法返回字典键的教程
May 21 Python
Python实现PS图像明亮度调整效果示例
Jan 23 Python
Python元组常见操作示例
Feb 19 Python
pandas DataFrame行或列的删除方法的实现示例
Aug 02 Python
python模拟鼠标点击和键盘输入的操作
Aug 04 Python
Python 3.8正式发布重要新功能一览
Oct 17 Python
Python实现隐马尔可夫模型的前向后向算法的示例代码
Dec 31 Python
Python reversed函数及使用方法解析
Mar 17 Python
Python通过socketserver处理多个链接
Mar 18 Python
基于Python的OCR实现示例
Apr 03 Python
keras中的卷积层&amp;池化层的用法
May 22 Python
Python爬虫实战之爬取京东商品数据并实实现数据可视化
Jun 07 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 URL编码解码函数代码
2009/03/10 PHP
解析php php_openssl.dll的作用
2013/07/01 PHP
简单介绍win7下搭建apache+php+mysql开发环境
2015/08/06 PHP
简单谈谈PHP中的Reload操作
2016/12/12 PHP
详解PHP文件的自动加载(autoloading)
2018/02/04 PHP
Laravel 读取 config 下的数据方法
2019/10/13 PHP
超级简单的图片防盗(HTML),好用
2007/04/08 Javascript
js控制的遮罩层实例介绍
2013/05/29 Javascript
jQuery制作简洁的多级联动Select下拉框
2014/12/23 Javascript
JQuery显示隐藏DIV的方法及代码实例
2015/04/16 Javascript
简介AngularJS的HTML DOM支持情况
2015/06/17 Javascript
jQuery EasyUI基础教程之EasyUI常用组件(推荐)
2016/07/15 Javascript
js实现对table的增加行和删除行的操作方法
2016/10/13 Javascript
基于JavaScript实现下拉列表左右移动代码
2017/02/07 Javascript
vue-router判断页面未登录自动跳转到登录页的方法示例
2018/11/04 Javascript
mpvue+vant app搭建微信小程序的方法步骤
2019/02/11 Javascript
vue 解决异步数据更新问题
2019/10/29 Javascript
python中合并两个文本文件并按照姓名首字母排序的例子
2014/04/25 Python
使用Python中的cookielib模拟登录网站
2015/04/09 Python
Python实现获取域名所用服务器的真实IP
2015/10/25 Python
Python实现遍历目录的方法【测试可用】
2017/03/22 Python
Python2.7基于笛卡尔积算法实现N个数组的排列组合运算示例
2017/11/23 Python
Python OpenCV 直方图的计算与显示的方法示例
2018/02/08 Python
Python修改文件往指定行插入内容的实例
2019/01/30 Python
python GUI库图形界面开发之PyQt5信号与槽事件处理机制详细介绍与实例解析
2020/03/08 Python
学python需要去培训机构吗
2020/07/01 Python
分享全球十款超强HTML5开发工具
2014/05/14 HTML / CSS
怎样自定义一个异常类
2016/09/27 面试题
工商管理实习自我鉴定
2013/09/28 职场文书
经典公益广告词
2014/03/13 职场文书
爱耳日活动总结
2014/04/30 职场文书
2014年安全员工作总结
2014/11/13 职场文书
社区法制宣传日活动总结
2015/05/05 职场文书
2015年幼儿园卫生保健工作总结
2015/05/12 职场文书
导游词之潮音寺
2019/09/26 职场文书
python编程实现清理微信重复缓存文件
2021/11/01 Python