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 相关文章推荐
python3 实现的人人影视网站自动签到
Jun 19 Python
Python编程判断这天是这一年第几天的方法示例
Apr 18 Python
浅谈DataFrame和SparkSql取值误区
Jun 09 Python
基于Python pip用国内镜像下载的方法
Jun 12 Python
Python脚本操作Excel实现批量替换功能
Nov 20 Python
用pytorch的nn.Module构造简单全链接层实例
Jan 14 Python
tensorflow 初始化未初始化的变量实例
Feb 06 Python
如何安装并在pycharm使用selenium的方法
Apr 30 Python
keras 实现轻量级网络ShuffleNet教程
Jun 19 Python
详解numpy.ndarray.reshape()函数的参数问题
Oct 13 Python
使用Python Tkinter实现剪刀石头布小游戏功能
Oct 23 Python
Python基础数据类型tuple元组的概念与用法
Aug 02 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
实现“上一页”和“下一页按钮
2006/10/09 PHP
优化PHP代码的53条建议
2008/03/27 PHP
php生成略缩图代码
2012/07/16 PHP
php中mysql连接方式PDO使用详解
2015/02/25 PHP
PHP模板引擎Smarty中变量的使用方法示例
2016/04/11 PHP
php利用header函数下载各种文件
2016/08/24 PHP
Mootools 1.2教程 选项卡效果(Tabs)
2009/09/15 Javascript
图片动画横条广告带上下滚动可自定义图片、链接等等
2013/10/20 Javascript
原生js仿jq判断当前浏览器是否为ie,精确到ie6~8
2014/08/30 Javascript
如何编写高质量JS代码(续)
2015/02/25 Javascript
javascript实现图像循环明暗变化的方法
2015/02/25 Javascript
JavaScript面试开发常用的知识点总结
2016/08/08 Javascript
Javascript从数组中随机取出不同元素的两种方法
2016/09/22 Javascript
Easyui的组合框的取值与赋值
2016/10/28 Javascript
利用vue写todolist单页应用
2016/12/15 Javascript
JavaScript 函数的定义-调用、注意事项
2017/04/16 Javascript
vue loadmore 组件滑动加载更多源码解析
2017/07/19 Javascript
JavaScript实现离开页面前提示功能【附jQuery实现方法】
2017/09/26 jQuery
vue 系列——vue2-webpack2框架搭建踩坑之路
2017/12/22 Javascript
微信小程序视图容器(swiper)组件创建轮播图
2020/06/19 Javascript
webstorm中配置Eslint的两种方式及差异比较详解
2018/10/19 Javascript
Nodejs实现用户注册功能
2019/04/14 NodeJs
vue实现分页的三种效果
2020/06/23 Javascript
Python中的并发编程实例
2014/07/07 Python
深入解析Python的Tornado框架中内置的模板引擎
2016/07/11 Python
使用Python实现在Windows下安装Django
2018/10/17 Python
Python列表原理与用法详解【创建、元素增加、删除、访问、计数、切片、遍历等】
2019/10/30 Python
Python爬虫之Spider类用法简单介绍
2020/08/04 Python
澳大利亚首屈一指的在线购物目的地:Kogan.com
2017/02/02 全球购物
Java面试题:请说出如下代码的输出结果
2013/04/22 面试题
个人承诺书格式范文
2015/04/29 职场文书
单位病假条范文
2015/08/17 职场文书
如何解决.cuda()加载用时很长的问题
2021/05/24 Python
go语言中http超时引发的事故解决
2021/06/02 Golang
Python机器学习实战之k-近邻算法的实现
2021/11/27 Python
MYSQL事务的隔离级别与MVCC
2022/05/25 MySQL