截取bin文件内容,指定位置和长度

方法一:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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 后面的所有字符被删除。
使用方法:

1
fileObject.truncate( [ size ])

truncate用法点击此链接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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