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)
    

      

  • 相关阅读:
    eclipse debug小技巧
    session.flush加锁测试.
    mac os x升级MOUNTAIN LION后svn command not found的解决
    Linux下vi命令大全(转)
    Java 集合框架
    java 实用类
    Java 输入/输出 反射
    Java 注解
    多线程(重点)
    多线程
  • 原文地址:https://www.cnblogs.com/SunshineKimi/p/12937337.html
Copyright © 2011-2022 走看看