方法一:
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) strContent = f1.read(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
|