Use Python struct

Source: Internet
Author: User
Python struct module

The main content from: http://blog.163.com/sywxf@126/blog/static/50671196201011319507710/

 

Simply read a binary file:

 
# coding: utf-8

 

import struct

import sys

binfile=open('test.bin','rb')

buf = binfile.read()

unpackIndex = 0

a,b,c,d = struct.unpack_from('ifdh', buf, unpackIndex)

print a, b, c, d

unpackIndex += struct.calcsize('ifdh')

 

This file stores a struct

Struct ABC {

Int;

Float B;

Double C;

Short D;

};

 

The C ++ code is:

// Writeandreadbin. cpp: defines the entry point of the console application.

//

 

#include "stdafx.h"

 

 

#include<fstream>

#include <iostream>

using namespace std;

void main()

{

    ofstream fwrite("test.bin", ios::out | ios::app | ios::binary);

    if(!fwrite){

        cout<<"File open error!\n";

        return;

    }

 

    int a = 0x12345678;

    float b = 3.25;

    double c = 4.33;

    short d = 0x2468;

    fwrite.write((char*)&a, sizeof(a));

    fwrite.write((char*)&b, sizeof(b));

    fwrite.write((char*)&c, sizeof(c));

    fwrite.write((char*)&d, sizeof(d));

 

    fwrite.close();

 

    ifstream fread("test.bin", ios::in|ios::binary);

    if(!fread)

    {

        cout<<"File open error!"<<endl;

        return;

    }

    fread.read((char*)&a, sizeof(a));

    fread.read((char*)&b, sizeof(b));

    fread.read((char*)&c, sizeof(c));

    fread.read((char*)&d, sizeof(d));

    fread.close();

 

    cout<<a<<endl;

    cout<<b<<endl;

    cout<<c<<endl;

    cout<<d<<endl;

}

 

Python is used to read some simple structure files. The following binary files are read and related field values are displayed:

#!usr/bin/env python

# coding: utf-8

# read_codefilelist.py

 

'''

typedef struct SecuCodeNewFileItem

{

Unsigned int secucode; // securities code

Unsigned char secuname [20]; // securities name,

Unsigned int markettype; // New Market Type

    signed char        Jianpin[8];

Float pervclose; // collect

Float last5av; // average volume per minute in the past 5 days, used for computing Ratio

Float circulation; // circulation Disk

}structSecuCodeNewFileItem;

'''

import struct

import sys

 

type = sys.getfilesystemencoding()

 

binfile=open('codelist_pad.dat','rb')

buf = binfile.read()

unpackIndex = 0

count = struct.unpack_from('i', buf, unpackIndex)

unpackIndex += struct.calcsize('i')

print 'count=', count[0]

 

for i in range(0, count[0], 1):

    SecuCode,\

    SecuName,    \

    MarketType,  \

    Jianpin, \

    PervClose, \

    Last5AV, \

    Circulation = struct.unpack_from('i20si8sfff', buf, unpackIndex)

    

    print '%06d'%SecuCode, MarketType, \

          SecuName.decode(encoding='UTF-8', errors='ignore').rstrip('\000')

 

    unpackIndex += struct.calcsize('i20si8sfff')

    

 

name = input("Please input any key to exit:\n")

 

Later, I thought about it. The previous writing method is still a little troublesome. The purpose of using python is to speed up. The previous writing method is inconvenient when the structure needs to be changed. The following is faster:

#!usr/bin/env python

# coding: utf-8

# read_codefilelist.py

 

'''

typedef struct SecuCodeNewFileItem

{

Unsigned int secucode; // securities code

Unsigned char secuname [20]; // securities name,

Unsigned int markettype; // New Market Type

    signed char        Jianpin[8];

Float pervclose; // collect

Float last5av; // average volume per minute in the past 5 days, used for computing Ratio

Float circulation; // circulation Disk

}structSecuCodeNewFileItem;

'''

import struct

import sys

 

type = sys.getfilesystemencoding()

 

binfile=open('codelist_pad.dat','rb')

buf = binfile.read()

unpackIndex = 0

count = struct.unpack_from('i', buf, unpackIndex)

unpackIndex += struct.calcsize('i')

print 'count=', count[0]

 

for i in range(0, count[0], 1):

    data = struct.unpack_from('i20si8sfff', buf, unpackIndex)

    print '%06d'%data[0], data[2],\

          data[1].decode(encoding='UTF-8', errors='ignore').rstrip('\000')

    

    unpackIndex += struct.calcsize('i20si8sfff')

    

    

name = input("Please input any key to exit:\n")

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.