Python struct.pack () binary files, storage and parsing of packaged binary data in files

Source: Internet
Author: User

In the process of learning Python, there is a problem, in the Python Learning Manual (also known as "Learning Python"), in tuples, files, and other chapters, there is a piece of code that deals with binary files:

>>>f=open (' Data.bin ', ' WB ')

>>>import struct

>>>data=struct.pack (' I4sh ', 7, ' spam ', 8)

>>>data

B ' \x00\x00\x00\x07spam\x00\x08 '

>>>f.write (data) \

>>>f.close ()

In fact, either in Python 2.x or 3.x, perform the third step Data=struct,pack (...) , the output will be error, error:

Traceback (most recent):

  File "<pyshell#3>", line 1, in <module>

Data=struct.pack (' >i4sh ', 7, ' spam ', 8)
Struct.error:argument for ' s ' must is a bytes object

  To view the Help documentation, you can see the description:

ructstruct.pack(fmt, v1, v2, ... ) )

Return a Bytes object containing the values v1, v2,? Packed according to the format string fmt. The arguments must match the values required by the format exactly.

The value of the formatted string and then the type in Python is the bytes type, so we need to do the processing. → Add a b before the bytes type to solve the problem.

>>>data=struct,pack (' >i4sh ', 7,b ' spam ', 8)

B ' \x00\x00\x00\x07spam\x00\x08 '

  To solve this problem!

Struct.pack (fmt,v1,v2.), FMT is a Linux command that functions as an orchestration of text files. Do not make too many records here.

# encapsulates data into a string (actually a byte stream similar to a C struct) in the given format (FMT)

By the way, the introduction of ' >i4sh ', its data structure in C data structure and Python:

I-->int-->integer--->7

4s-->char-->string---> ' spam '

h-->unsigned short-->integer-->8

  

  

Python struct.pack () binary files, storage and parsing of packaged binary data in files

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.