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查找目录下指定扩展名的文件实例
Apr 01 Python
Python实现线程池代码分享
Jun 21 Python
python 禁止函数修改列表的实现方法
Aug 03 Python
python Pygame的具体使用讲解
Nov 03 Python
python 使用正则表达式按照多个空格分割字符的实例
Dec 20 Python
实例讲解Python中浮点型的基本内容
Feb 11 Python
对Python 中矩阵或者数组相减的法则详解
Aug 26 Python
python爬虫中多线程的使用详解
Sep 23 Python
Python实现栈的方法详解【基于数组和单链表两种方法】
Feb 22 Python
python标准库OS模块详解
Mar 10 Python
Python使用plt.boxplot() 参数绘制箱线图
Jun 04 Python
python字符串的多行输出的实例详解
Jun 08 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伪静态之APACHE篇
2014/06/02 PHP
php开发微信支付获取用户地址
2015/10/04 PHP
JS 显示当前日期与时间的代码
2010/03/24 Javascript
关于js注册事件的常用方法
2013/04/03 Javascript
使用JS读秒使用示例
2013/09/21 Javascript
Bootstrap进度条组件知识详解
2016/05/01 Javascript
bootstrap日期控件问题(双日期、清空等问题解决)
2017/04/19 Javascript
你可能不知道的JSON.stringify()详解
2017/08/17 Javascript
JSON在Javascript中的使用(eval和JSON.parse的区别)详细解析
2017/09/05 Javascript
javascript  删除select中的所有option的实例
2017/09/17 Javascript
MUI 实现侧滑菜单及其主体部分上下滑动的方法
2018/01/25 Javascript
微信小程序实现购物页面左右联动
2019/02/15 Javascript
vue响应式系统之observe、watcher、dep的源码解析
2019/04/09 Javascript
vue路由拦截器和请求拦截器知识点总结
2019/11/08 Javascript
[04:27]DOTA2官方论坛水友赛集锦
2013/09/16 DOTA
[00:27]DOTA2战队VP、Secret贺新春
2018/02/11 DOTA
Python的自动化部署模块Fabric的安装及使用指南
2016/01/19 Python
python Flask实现restful api service
2017/12/04 Python
详解python3中tkinter知识点
2018/06/21 Python
django admin 自定义替换change页面模板的方法
2019/08/23 Python
基于Python模拟浏览器发送http请求
2020/11/06 Python
复古风格的女装和装饰品:ModCloth
2017/12/29 全球购物
俄罗斯第一家多品牌在线奢侈品精品店:Aizel.ru
2020/09/06 全球购物
军训自我鉴定范文
2014/02/13 职场文书
小学老师寄语大全
2014/04/04 职场文书
环保专项行动方案
2014/05/12 职场文书
美化环境标语
2014/06/20 职场文书
大专毕业生求职信
2014/07/05 职场文书
村党支部书记个人对照材料汇报
2014/10/26 职场文书
2014年店长工作总结
2014/11/17 职场文书
小学班主任评语
2014/12/29 职场文书
中学社团活动总结
2015/05/07 职场文书
社区党建工作总结2015
2015/05/13 职场文书
小学生纪律委员竞选稿
2015/11/19 职场文书
python 提取html文本的方法
2021/05/20 Python
python ansible自动化运维工具执行流程
2021/06/24 Python