Python分割文件以及合并文件

本文介绍了使用Python进行文件分割和合并的方法。通过split_file.py和join_file.py两个脚本,实现了按照指定大小分割文件,并能将分割后的部分重新合并。这两个脚本适用于Windows和Unix系统,具有良好的可移植性和可配置性。
摘要由CSDN通过智能技术生成
用Python进行文件操作是比较简单的,在Python中file是内置类型之一,内置的函数open、file都可以创建file对象,创建好之后就可以对其进行读写等操作。

近几天看Python Programing 3rd ,觉得书很不错。

文件分割的原理很简单:以二进制形式打开文件流,按照指定的大小读取,然后写入新文件。
文件合并的原理正好相反。

下面的代码摘自PP3rd里面。

split_file.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
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值