python截取二进制文件

接到任务,截取dat文件,每个数据784个字节,现要取一定百分比的数据
主要涉及了python文件读写,命令行参数使用

# -*- coding: utf-8 -*-

import sys
import os

if __name__ == "__main__":
    datPath = sys.argv[1]
    pst = sys.argv[2]
    k = float(pst)
    datOut = datPath[0:-4]+str(k)+"%.dat"
    k = k/100.0
    try:
        datIn = open(datPath,"rb")
        datOut = open(datOut, "wb")
    except Exception,e:
        print e;
        exit(-2)
    size = os.path.getsize(datPath)
    nIn = size/784
    nOut = int(nIn*k)
    try:
        for i in range(0,nOut):
            temp = datIn.read(784)
            datOut.write(temp)
    finally:
        datIn.close()
        datOut.close()


你可能感兴趣的:(Python)