Home  >  Article  >  Backend Development  >  How to use Python to read and write binary files

How to use Python to read and write binary files

WBOY
WBOYforward
2023-05-03 12:40:063044browse

1. Introduction

Python needs to use the struct module to read and write binary data of files to convert C/C and Python data formats.

2. Introduction to struct module

The most commonly used functions in the struct module are pack and unpack. The usage is as follows:

##pack_into(fmt,buffer,offset, v1, v2...)NoneConvert 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)unpack(fmt,v1,v2……)tupleParse the byte stream according to the given format (fmt) and return the parsing resultpack_from(fmt,buffer,offset)tupleParse the buffer starting with offset according to the given format (fmt) and return the parsing result##calcsize(fmt)3. The data format fmt in the struct module corresponds to C/C and Python Type in
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.
size of fmt Calculate how many bytes of memory the given format (fmt) occupies, pay attention to the alignment

FormatxcbB?##hshortinteger 2Hunsigned shortinteger2iintinteger4unsigned intlongunsigned longlong longunsigned long long##ffloatfloat4ddoublefloat8schar[]stringchar[]stringvoid *integerNote: In the code, 9754dae2addc9a84fb2641be7b7586b0 means big endian
import struct

# 打开文件
with open("binary_file.bin", "wb") as f:

    # 写入4个字节的整数(值为12345)
    int_value = 12345
    f.write(struct.pack("<i", int_value))

    # 写入8个字节的双精度浮点数(值为3.14159)
    double_value = 3.14159
    f.write(struct.pack("<d", double_value))

    # 写入一个字节的布尔值(值为True)
    bool_value = True
    f.write(struct.pack("<?", bool_value))

    # 写入一个定长字符串(10个字符,值为"hello")
    string_value = "hello".encode("utf-8")
    f.write(struct.pack("<5s", string_value))

    # 写入一个定长字节数组(20个字节,值为b"\x01\x02\x03...\x14")
    byte_array_value = bytes(range(1, 21))
    f.write(struct.pack("<20s", byte_array_value))

    f.close()

# 打开文件
with open("binary_file.bin", "rb") as f:

    # 读取4个字节,解析成一个整数
    int_value = struct.unpack("<i", f.read(4))[0]
    
    # 读取8个字节,解析成一个双精度浮点数
    double_value = struct.unpack("<d", f.read(8))[0]

    # 读取一个字节,解析成一个布尔值
    bool_value = struct.unpack("<?", f.read(1))[0]

    # 读取一个字符串,解析成一个定长字符串(10个字符)
    string_value = struct.unpack("<5s", f.read(5))[0].decode("utf-8")

    # 读取一个字节数组,解析成一个定长字节数组(20个字节)
    byte_array_value = struct.unpack("<20s", f.read(20))[0]

    # 打印结果
    print(f"int_value: {int_value}")
    print(f"double_value: {double_value}")
    print(f"bool_value: {bool_value}")
    print(f"string_value: {string_value}")
    print(f"byte_array_value: {byte_array_value}")

    f.close()
5. The meaning of adding u, r, b, f in front of a Python string
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
##I
integer 4 l
integer 4 L
integer 4 q
integer 8 Q
integer 8
p
P
##4. Example

5.1 . Add u

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&#39;hello&#39;

5.2. Add r

in front of the string to remove the backslash transfer mechanism. (Special characters: that is, those, backslash plus corresponding letters, indicating the corresponding special meaning, such as the most common "\n" means line break, "\t" means Tab, etc.)

str= r&#39;hello\n\t\n&#39;

5.3 . Adding b

before a string indicates that the string is of bytes type.

bytes = b&#39;hello&#39;

In Python3, the mutual conversion method between bytes and str is

str.encode(‘utf-8&#39;)
bytes.decode(‘utf-8&#39;)

5.4. Add f

before the string and start with f to indicate that curly braces are supported within the string. python expression, string concatenation

name = &#39;Lily&#39;
print(f&#39;My name is {name}.&#39;)

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete