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小技巧分享
Nov 22 Python
Python中atexit模块的基本使用示例
Jul 08 Python
Python基于有道实现英汉字典功能
Jul 25 Python
浅谈python字符串方法的简单使用
Jul 18 Python
Python cookbook(数据结构与算法)根据字段将记录分组操作示例
Mar 19 Python
Python数据持久化shelve模块用法分析
Jun 29 Python
python list多级排序知识点总结
Oct 23 Python
如何基于python操作excel并获取内容
Dec 24 Python
pytorch中使用cuda扩展的实现示例
Feb 12 Python
Tensorflow训练MNIST手写数字识别模型
Feb 13 Python
如何用python反转图片,视频
Apr 24 Python
Python实现天气查询软件
Jun 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
关于我转生变成史莱姆这档事:第二季PV上线,萌王2021年回归
2020/05/06 日漫
自己动手做一个SQL解释器
2006/10/09 PHP
PHP explode()函数用法、切分字符串
2012/10/03 PHP
destoon网站转移服务器后搜索汉字出现乱码的解决方法
2014/06/21 PHP
linux下编译安装memcached服务
2014/08/03 PHP
PHP中的socket_read和socket_recv区别详解
2015/02/09 PHP
[原创]php token使用与验证示例【测试可用】
2017/08/30 PHP
laravel-admin 实现在指定的相册下添加照片
2019/10/21 PHP
[原创]提供复制本站内容时出现,该文章转自脚本之家等字样的js代码
2007/03/27 Javascript
一些经常会用到的Javascript检测函数
2010/05/31 Javascript
js网页实时倒计时精确到秒级
2014/02/10 Javascript
javascript表单验证和Window详解
2014/12/11 Javascript
跟我学习javascript的作用域与作用域链
2015/11/19 Javascript
Sortable.js拖拽排序使用方法解析
2016/11/04 Javascript
JS实现按钮添加背景音乐示例代码
2017/10/17 Javascript
jquery在启动页面时,自动加载数据的实例
2018/01/22 jQuery
JavaScript实现构造json数组的方法分析
2018/08/17 Javascript
[49:31]DOTA2-DPC中国联赛 正赛 Elephant vs LBZS BO3 第二场 1月29日
2021/03/11 DOTA
使用pyecharts无法import Bar的解决方案
2020/04/23 Python
python3第三方爬虫库BeautifulSoup4安装教程
2018/06/19 Python
python面试题Python2.x和Python3.x的区别
2019/05/28 Python
Python 使用threading+Queue实现线程池示例
2019/12/21 Python
mac 上配置Pycharm连接远程服务器并实现使用远程服务器Python解释器的方法
2020/03/19 Python
html5桌面通知(Web Notifications)实例解析
2014/07/07 HTML / CSS
使用html2canvas.js实现页面截图并显示或上传的示例代码
2018/12/18 HTML / CSS
新西兰演唱会和体育门票网站:Ticketmaster新西兰
2017/10/07 全球购物
The Hut美国/加拿大:英国领先的豪华在线百货商店
2019/03/26 全球购物
可靠的数据流传输TCP
2016/03/15 面试题
超市仓管员岗位职责
2014/04/07 职场文书
优秀共产党员先进事迹材料
2014/05/06 职场文书
教师党的群众路线教育实践活动个人对照检查材料
2014/09/23 职场文书
2015年乡镇财政工作总结
2015/05/19 职场文书
为什么阅读对所有年龄段的孩子都很重要?
2019/07/08 职场文书
小学四年级作文之写景
2019/08/23 职场文书
深入理解margin塌陷和margin合并的解决方案
2021/06/26 HTML / CSS
Python的代理类实现,控制访问和修改属性的权限你都了解吗
2022/03/21 Python