Struct binary data module in Python

Source: Internet
Author: User

The struct module of Python is used to create and extract packaged binary data from strings.

Pack (fmt, v1, v2,...) encapsulates data into strings (actually byte streams similar to the c struct) in the given format (fmt ). Unpack (fmt, string) parses the byte stream string according to the given format (fmt) and returns the parsed tuple.


Write data to a binary file.

>>> F = open ('data. bin ', 'wb') >>> import struct >>> data = struct. pack ('> i4sh', 7, 'spam', 8) >>> datab' \ x00 \ x00 \ x00 \ x07spam \ x00 \ x08' >>> F. write (data) 10 >>> F. close ()


Read data from a binary file
>>> F = open ('data. bin', 'rb')> data = F. read () >>> datab' \ x00 \ x00 \ x00 \ x07spam \ x00 \ x08 '>>> import struct >>> values = struct. unpack ('> i4sh', data) >>> values (7, 'spam', 8)
Note that unpack returns a tuple object.

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.