zoukankan      html  css  js  c++  java
  • python 文件指针切割文件

    原理:

    file.seek(offset, whence)

    offset 偏移量,也就是相对于whence 的向前向后读取字节个数的值,可以负数,负数向前,整数向后,默认0

    whence 有两种表示方法:纯数字,python内置函数

    0,1,2 分别对应os.SEEK_SET,os.SEEK_CUR,os.SEEK_END

    0表示指针移动到文件起始位置0

    1表示指针移动到文件当前位置

    2表示指针移动到文件末尾位置

    案例:切割一个txt大小240字节的文件,每份50bytes,不够50取剩余全部,然后按顺序以二进制写入另一个文件保存

    import os
    import math
    
    
    def cut_file(f):
        fp=open("./test.txt","rb")
        file_length=os.path.getsize("./test.txt")
        cut_interval=50
        nums=math.ceil(float(file_length)/cut_interval)
        for i in range(nums):
            if i < nums-1 :
                byte_type=0  # complete cut_interval byte
                fp.seek(i * cut_interval, 0)
                byte= fp.read(cut_interval)
    
                print( f"[{byte_type}] byte get size : {len(byte)},pointer is {fp.tell()},
    {byte}")
            else:
                byte_type=1 # uncomleted cut_interval byte
                remain= file_length%cut_interval
                int_cut=file_length//cut_interval
                fp.seek(int_cut*cut_interval,0)
                byte=fp.read(remain)
                print( f"[{byte_type}] byte get size : {len(byte)},pointer is {fp.tell()},
    {byte}")
            f.write(byte)
    
    
    if __name__ == '__main__':
        with open("./dest.txt","wb")as f:
            cut_file(f)
    

      

  • 相关阅读:
    RAID实战案例
    文件系统常用工具实战篇
    挂载文件系统
    硬盘结构类型概述
    创建文件系统实战篇
    JumpServer的会话管理及命令过滤器应用案例
    JumpServer的权限管理
    JumpServer的用户管理
    helm基础
    hpa控制器
  • 原文地址:https://www.cnblogs.com/SunshineKimi/p/12937337.html
Copyright © 2011-2022 走看看