Python实现分割文件及合并文件的方法

 更新时间:2015年07月10日 16:57:39   作者:Sephiroth  
这篇文章主要介绍了Python实现分割文件及合并文件的方法,涉及Python针对文件的分割与合并操作相关技巧,通过自定义函数split与join实现了文件的分割与合并操作,需要的朋友可以参考下

本文实例讲述了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中opencv支持向量机的实现

    python中opencv支持向量机的实现

    本文主要介绍了python中opencv支持向量机的实现,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-03-03
  • 用python处理图片之打开\显示\保存图像的方法

    用python处理图片之打开\显示\保存图像的方法

    本篇文章主要介绍了用python处理图片之打开\显示\保存图像的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-05-05
  • Python中itertools简介使用介绍

    Python中itertools简介使用介绍

    itertools是python内置的模块,使用简单且功能强大,itertools模块标准化了一个快速、高效利用内存的核心工具集,这些工具本身或组合都很有用,这篇文章主要介绍了Python中itertools详解,需要的朋友可以参考下
    2022-12-12
  • Scrapy爬虫实例讲解_校花网

    Scrapy爬虫实例讲解_校花网

    下面小编就为大家带来一篇Scrapy爬虫实例讲解_校花网。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-10-10
  • 跟老齐学Python之折腾一下目录

    跟老齐学Python之折腾一下目录

    本讲只关注os.path,真所谓“弱水三千,只取一瓢”,为什么这么偏爱它呢?因为它和前面已经讲过的文件操作进行配合,就能够随心所欲操作各个地方的文件了
    2014-10-10
  • python中redis查看剩余过期时间及用正则通配符批量删除key的方法

    python中redis查看剩余过期时间及用正则通配符批量删除key的方法

    这篇文章主要介绍了python中redis查看剩余过期时间及用正则通配符批量删除key的方法,需要的朋友可以参考下
    2018-07-07
  • python实现根据指定字符截取对应的行的内容方法

    python实现根据指定字符截取对应的行的内容方法

    今天小编就为大家分享一篇python实现根据指定字符截取对应的行的内容方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-10-10
  • Python利用Diagrams绘制漂亮的系统架构图

    Python利用Diagrams绘制漂亮的系统架构图

    Diagrams  是一个基于Python绘制云系统架构的模块,它能够通过非常简单的描述就能可视化架构。本文将利用它绘制漂亮的系统架构图,感兴趣的可以了解一下
    2023-01-01
  • python神经网络Keras实现LSTM及其参数量详解

    python神经网络Keras实现LSTM及其参数量详解

    这篇文章主要为大家介绍了python神经网络Keras实现LSTM及其参数量详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-05-05
  • Python3.8对可迭代解包的改进及用法详解

    Python3.8对可迭代解包的改进及用法详解

    这篇文章主要介绍了Python3.8对可迭代解包的改进及用法详解,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-10-10

最新评论