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模拟百度登录实例详解
Jan 20 Python
python使用TensorFlow进行图像处理的方法
Feb 28 Python
Windows下python3.6.4安装教程
Jul 31 Python
python 用opencv调用训练好的模型进行识别的方法
Dec 07 Python
Python 微信之获取好友昵称并制作wordcloud的实例
Feb 21 Python
Python文件操作中进行字符串替换的方法(保存到新文件/当前文件)
Jun 28 Python
Python适配器模式代码实现解析
Aug 02 Python
python实现多进程通信实例分析
Sep 01 Python
tf.concat中axis的含义与使用详解
Feb 07 Python
jupyternotebook 撤销删除的操作方式
Apr 17 Python
python多线程爬取西刺代理的示例代码
Jan 30 Python
python推导式的使用方法实例
Feb 28 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 XML操作类DOMDocument
2009/12/16 PHP
ThinkPHP实现支付宝接口功能实例
2014/12/02 PHP
详解PHP函数 strip_tags 处理字符串缺陷bug
2017/06/11 PHP
Yii 2.0实现联表查询加搜索分页的方法示例
2017/08/02 PHP
ThinkPHP 3使用OSS的方法
2018/07/19 PHP
js简单实现让文本框内容逐个字的显示出来
2013/10/22 Javascript
如何判断鼠标是否在DIV的区域内
2013/11/13 Javascript
javascript实现节点(div)名称编辑
2014/12/17 Javascript
jquery实现简单的无缝滚动
2015/04/15 Javascript
javascript操作ul中li的方法
2015/05/14 Javascript
实例讲解js验证表单项是否为空的方法
2016/01/09 Javascript
JavaScript获取对象在页面中位置坐标的方法
2016/02/03 Javascript
ReactJs快速入门教程(精华版)
2016/11/28 Javascript
JavaScript、C# URL编码、解码总结
2017/01/21 Javascript
js 去掉字符串前后空格实现代码集合
2017/03/25 Javascript
慕课网题目之js实现抽奖系统功能
2017/09/19 Javascript
详解Vue-cli中的静态资源管理(src/assets和static/的区别)
2018/06/19 Javascript
解决vue this.$forceUpdate() 处理页面刷新问题(v-for循环值刷新等)
2018/07/26 Javascript
简单了解TypeScript中如何继承 Error 类
2019/06/21 Javascript
[45:59]EG vs OG 2018国际邀请赛小组赛BO2 第二场 8.17
2018/08/18 DOTA
使用Python进行稳定可靠的文件操作详解
2013/12/31 Python
Python 类与元类的深度挖掘 I【经验】
2016/05/06 Python
详解K-means算法在Python中的实现
2017/12/05 Python
win10系统下Anaconda3安装配置方法图文教程
2018/09/19 Python
python实现两张图片的像素融合
2019/02/23 Python
Python selenium抓取虎牙短视频代码实例
2020/03/02 Python
为什么相对PHP黑python的更少
2020/06/21 Python
Python3合并两个有序数组代码实例
2020/08/11 Python
Alba Moda德国网上商店:意大利时尚女装销售
2016/11/14 全球购物
Perfume’s Club德国官网:在线购买香水
2019/04/08 全球购物
教学质量评估实施方案
2014/03/17 职场文书
2014年个人债务授权委托书范本
2014/09/22 职场文书
工程部主管岗位职责
2015/02/12 职场文书
苹果可能正在打击不进行更新的 App
2022/04/24 数码科技
Python可视化神器pyecharts之绘制地理图表练习
2022/07/07 Python
vue本地构建热更新卡顿的问题“75 advanced module optimization”完美解决方案
2022/08/05 Vue.js