Python needs to use the struct module to read and write binary data of files to convert C/C and Python data formats.
The most commonly used functions in the struct module are pack and unpack. The usage is as follows:
Function | return | explain |
---|---|---|
pack(fmt,v1,v2…) | string | Convert the data into a string (byte stream) according to the given format (fmt), and return the string. |
None | Convert the data into a string (byte stream) according to the given format (fmt), and write the byte stream starting with offset In buffer. (buffer is a writable buffer, and the array module can be used) | |
tuple | Parse the byte stream according to the given format (fmt) and return the parsing result | |
tuple | Parse the buffer starting with offset according to the given format (fmt) and return the parsing result | |
size of fmt | Calculate how many bytes of memory the given format (fmt) occupies, pay attention to the alignment |
C Type | Python type | Standard size | |
---|---|---|---|
pad byte | no value | ||
char | string of length | 1 | |
signed char | integer | 1 | |
unsigned char | integer | 1 | |
_Bool | bool | 1 | ##h |
integer | 2 | H | |
integer | 2 | i | |
integer | 4 | ##I | |
integer | 4 | l | |
integer | 4 | L | |
integer | 4 | q | |
integer | 8 | Q | |
integer | 8 | ##f | float |
4 | d | double | |
8 | s | char[] | |
p | char[]|||
P | void *|||
##4. Example | Note: In the code, < means little endian, > means big endian
in front of the string and the following string is encoded in Unicode format. It is generally used in front of Chinese strings to prevent garbled characters when used again due to source code storage format issues.
str= u'hello'
str= r'hello\n\t\n'
5.3 . Adding b
bytes = b'hello'
In Python3, the mutual conversion method between bytes and str is
str.encode(‘utf-8') bytes.decode(‘utf-8')
before the string and start with f to indicate that curly braces are supported within the string. python expression, string concatenation
name = 'Lily' print(f'My name is {name}.')
The above is the detailed content of How to use Python to read and write binary files. For more information, please follow other related articles on the PHP Chinese website!