两种方法实现截取文件内容: 指定位置和长度, 截取文件的内容

遇到一个小需求: 如何提取一个bin文件中的内容, 前提是指定提取的开始位置, 和提取内容的长度.

方法一:

import os

def cutBinFile(strFile, iStart=0, iLength=None):
    if iLength is None:
        iLength = os.path.getsize(strFile)
    if  not os.path.exists(strFile):
        print("%s is not exist"%strFile)
        return False
    with open(strFile, "rb") as  f1:
        f1.seek(iStart, 0)         # 0 表示从文件开头开始算起,  第一个参数表示定位到该位置
        strContent = f1.read(iLength)   # 读取 iLength 这么多的内容
        strNewFile = strFile + ".bin"      # 给新文件命名, 后缀自己决定
        with open(strNewFile, "wb") as f2:
            f2.write(strContent)
    return True

方法二:
python内置了文件处理的方法

truncate() 方法用于截断文件,如果指定了可选参数 size,则表示截断文件为 size 个字符。 如果没有指定 size,则从当前位置起截断;截断之后 size 后面的所有字符被删除。
使用方法:

fileObject.truncate( [ size ])

truncate用法点击此链接

def cutBinFile2(strFile, iStart=0, iLength=None):
    if iLength is None:
        iLength = os.path.getsize(strFile)
    if  not os.path.exists(strFile):
        print("%s is not exist"%strFile)
        return False
    with open(strFile, "rb+") as  f1:
        f1.seek(iStart, 0)
        f1.truncate(iLength)
        strContent = f1.read()
        strNewFile = strFile + "new.bin"
        with open(strNewFile, "wb") as f2:
            f2.write(strContent)
    return True
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值