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