python 文件指针_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()},\n{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()},\n{byte}")

f.write(byte)

if __name__ == '__main__':

with open("./dest.txt","wb")as f:

cut_file(f)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值