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脚本实现下载合并SAE日志
Feb 10 Python
基于Python __dict__与dir()的区别详解
Oct 30 Python
Python scikit-learn 做线性回归的示例代码
Nov 01 Python
python enumerate函数的使用方法总结
Nov 15 Python
python 批量修改/替换数据的实例
Jul 25 Python
用xpath获取指定标签下的所有text的实例
Jan 02 Python
python按行读取文件并找出其中指定字符串
Aug 08 Python
django项目用higcharts统计最近七天文章点击量
Aug 17 Python
python实现KNN分类算法
Oct 16 Python
PyTorch实现更新部分网络,其他不更新
Dec 31 Python
以SQLite和PySqlite为例来学习Python DB API
Feb 05 Python
python中取整数的几种方法
Nov 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 header函数分析详解
2011/08/06 PHP
php中一个有意思的日期逻辑处理
2012/03/25 PHP
thinkphp配置文件路径的实现方法
2016/08/30 PHP
Yii2下点击验证码的切换实例代码
2017/03/14 PHP
用JavaScript事件串连执行多个处理过程的方法
2007/03/09 Javascript
jQuery 使用手册(五)
2009/09/23 Javascript
一个简单的网站访问JS计数器 刷新1次加1次访问
2012/09/20 Javascript
查看大图功能代码jquery版
2013/11/05 Javascript
jquery实现图片上传之前预览的方法
2015/07/11 Javascript
JS实现自动变换的菜单效果代码
2015/09/09 Javascript
javascript实现tab切换的两个实例
2015/11/05 Javascript
jQuery插件FusionCharts实现的3D柱状图效果实例【附demo源码下载】
2017/03/03 Javascript
详解Windows下安装Nodejs步骤
2017/05/18 NodeJs
解决JS外部文件中文注释出现乱码问题
2017/07/09 Javascript
详解JavaScript 中 if / if...else...替换方式
2018/07/15 Javascript
详解webpack2异步加载套路
2018/09/14 Javascript
uni-app之APP和小程序微信授权方法
2019/05/09 Javascript
如何使用JavaScript实现无缝滚动自动播放轮播图效果
2020/08/20 Javascript
解决谷歌搜索技术文章时打不开网页问题的python脚本
2013/02/10 Python
python获取文件扩展名的方法
2015/07/06 Python
python开发游戏的前期准备
2019/05/05 Python
详解Python3中setuptools、Pip安装教程
2019/06/18 Python
python使用hdfs3模块对hdfs进行操作详解
2020/06/06 Python
Python Map 函数的使用
2020/08/28 Python
python用opencv 图像傅里叶变换
2021/01/04 Python
CSS3教程(9):设置RGB颜色
2009/04/02 HTML / CSS
印度尼西亚最完整和最大的在线药房网站:Farmaku.com
2019/11/23 全球购物
应届大学生简历中的自我评价
2014/01/15 职场文书
竞选学生会主席演讲稿
2014/04/24 职场文书
优秀教导主任事迹材料
2014/05/09 职场文书
计生工作先进事迹
2014/08/15 职场文书
个人向公司借款协议书
2014/10/09 职场文书
校园开放日新闻稿
2015/07/17 职场文书
创业计划书之儿童理发店
2019/09/27 职场文书
创业计划书之熟食店
2019/10/16 职场文书
Python 中数组和数字相乘时的注意事项说明
2021/05/10 Python