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写的PHPMyAdmin暴力破解工具代码
Aug 06 Python
跟老齐学Python之有容乃大的list(3)
Sep 15 Python
Python中的super()方法使用简介
Aug 14 Python
web.py 十分钟创建简易博客实现代码
Apr 22 Python
解决tensorflow测试模型时NotFoundError错误的问题
Jul 26 Python
Python 通过调用接口获取公交信息的实例
Dec 17 Python
对python中的try、except、finally 执行顺序详解
Feb 18 Python
python自动化测试无法启动谷歌浏览器问题
Oct 10 Python
tensorflow实现对张量数据的切片操作方式
Jan 19 Python
浅谈keras中的后端backend及其相关函数(K.prod,K.cast)
Jun 29 Python
python利用后缀表达式实现计算器功能
Feb 22 Python
Python激活Anaconda环境变量的详细步骤
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
一些操作和快捷键的理解和讨论
2020/03/04 星际争霸
PHP中显示格式化的用户输入
2006/10/09 PHP
PHP4(windows版本)中的COM函数
2006/10/09 PHP
php 不使用js实现页面跳转
2014/02/11 PHP
PHP的命令行命令使用指南
2015/08/18 PHP
php使用parse_str实现查询字符串解析到变量中的方法
2017/02/17 PHP
Yii2框架自定义类统一处理url操作示例
2019/05/25 PHP
不常用但很实用的PHP预定义变量分析
2019/06/25 PHP
phpStorm2020 注册码
2020/09/17 PHP
学习js所必须要知道的一些
2007/03/07 Javascript
js parentElement和offsetParent之间的区别
2010/03/23 Javascript
javascript 异步页面查询实现代码(asp.net)
2010/05/26 Javascript
js 获取后台的字段 改变 checkbox的被选中的状态 代码
2013/06/05 Javascript
单元选择合并变色示例代码
2014/05/26 Javascript
网站接入QQ登录的两种方法
2014/07/22 Javascript
node.js中的Socket.IO使用实例
2014/11/04 Javascript
Jquery动态替换div内容及动态展示的方法
2015/01/23 Javascript
JS实现日期时间动态显示的方法
2015/12/07 Javascript
JavaScript对象数组排序函数及六个用法
2015/12/23 Javascript
js绑定事件和解绑事件
2017/04/27 Javascript
使用vue制作探探滑动堆叠组件的实例代码
2018/03/07 Javascript
基于Vue实现图片在指定区域内移动的思路详解
2018/11/11 Javascript
javascript数组常见操作方法实例总结【连接、添加、删除、去重、排序等】
2019/06/13 Javascript
vue.js的状态管理vuex中store的使用详解
2019/11/08 Javascript
Node.js API详解之 util模块用法实例分析
2020/05/09 Javascript
python实现判断数组是否包含指定元素的方法
2015/07/15 Python
Python中read()、readline()和readlines()三者间的区别和用法
2017/07/30 Python
Python、 Pycharm、Django安装详细教程(图文)
2019/04/12 Python
RUIFIER官网:英国奢侈高级珠宝品牌
2020/06/12 全球购物
一家外企的面试题目(C/C++面试题,C语言面试题)
2014/03/24 面试题
社区十八大感言
2014/01/19 职场文书
《会走路的树》教后反思
2014/04/19 职场文书
创业女性典型材料
2014/05/02 职场文书
公路绿化方案
2014/05/12 职场文书
大学生赌博检讨书
2014/09/22 职场文书
2015国庆节66周年演讲稿
2015/03/20 职场文书