python struct使用

來源:互聯網
上載者:User
python struct模組

主要內容來自轉自:http://blog.163.com/sywxf@126/blog/static/50671196201011319507710/

 

簡單讀一個二進位檔案:

 
# 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')

 

此檔案儲存體一個結構體

struct abc{

int a;

float b;

double c;

short d;

};

 

c++代碼為:

// writeandreadbin.cpp : 定義控制台應用程式的進入點。

//

 

#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用以做一些簡單的結構檔案的讀取還是很不錯的,如下讀取的二進位檔案,顯示出相關欄位值:

#!usr/bin/env python

# coding: utf-8

# read_codefilelist.py

 

'''

typedef struct SecuCodeNewFileItem

{

    unsigned int    SecuCode;       // 證券代碼

    unsigned char    SecuName[20];   // 證券名稱,

    unsigned int    MarketType;     // 新市場類型

    signed char        Jianpin[8];

    float            PervClose;      // 昨收

    float            Last5AV;        // 過去5日平均每分鐘成交量,用於計算量比

    float            Circulation;    // 流通盤

}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")

 

後來想了一下,前面的寫法還是有點麻煩,用python目的就是為了快,前面的寫法在需要改結構的時候,顯得很不方便,以下更快一點:

#!usr/bin/env python

# coding: utf-8

# read_codefilelist.py

 

'''

typedef struct SecuCodeNewFileItem

{

    unsigned int    SecuCode;       // 證券代碼

    unsigned char    SecuName[20];   // 證券名稱,

    unsigned int    MarketType;     // 新市場類型

    signed char        Jianpin[8];

    float            PervClose;      // 昨收

    float            Last5AV;        // 過去5日平均每分鐘成交量,用於計算量比

    float            Circulation;    // 流通盤

}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")

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.