[Reprinted] Python read and write binary files

Original address: https://blog.csdn.net/and_then111/article/details/86744938

1. What is a .bin file

A file with a .bin extension is a binary file. Unlike text files, binary files opened with Notepad, Notepad ++, etc. are garbled.
It
Opened a .bin file with Notepad
looks like this: But .bin files can be opened with software such as WINHEX. All the data stored in the binary file can only be understood by reading out according to a predetermined rule.

WINHEX converts the contents of binary files into hexadecimal format:
Opened a .bin file with WINHEX
the advantages of binary files compared to text files: saving storage space, fast reading and writing, and certain encryption protection.

About binary files and text files, you can refer to this blog programmer don't bluff me series: binary files

2. Read and write binary files

2.1 Reading binary files

Read the contents of the binary file "x.bin" and output one byte at a time.
(1) Put the file path filepathin, here the .bin file and the code file are placed in the same folder, so no absolute path is written.

(2) open(filepath, 'rb'): Open the file in the form of reading, pay attention to userb To read the binary file.

(3) Remember to close: binfile.close()

import struct
import os
if __name__ == '__main__':
    filepath='x.bin'
    binfile = open(filepath, 'rb') #打开二进制文件
    size = os.path.getsize(filepath) #获得文件大小
    for i in range(size):
        data = binfile.read(1) #每次输出一个字节
        print(data)
    binfile.close()

Run, output the result:
result

If you want to see the decimal result, you can use the struct.unpack () method in Python:: The meaning of
struct.unpack('B', data)the parameter here Bis to convert the unsigned char type of the C structure data to integer in Python.
The num obtained here is the tuple type, so Use num[0]to remove the number.

for i in range(size):
    data = binfile.read(1)
    num = struct.unpack('B', data)
    print(num[0])

The output is:
Insert picture description here

2.2 Writing binary files

(1) Suppose you want to write the number 123 to a binary file, you first need to convert the number int type to bytes type.
data.to_bytes(1, 'big'): Parameter ' 1': converted to 1 byte bytes; parameter 'big': byteorder.

View athe type of a variable , you can usetype()

a=123
print('a:',type(a))
b=a.to_bytes(1,'big')
print('b:',type(b))

Output:

(2) open(filepath, 'ab+'): Open binary file in write mode.
Note when writing: usefrom + To complete the additional write, use wbTo complete the overwrite.

(3) Closebinfile.close()

data=123
content= data.to_bytes(1, 'big')

filepath='123.bin'
binfile = open(filepath, 'ab+') #追加写入
binfile.write(content)
print('content',content)
binfile.close()

2.3 Open file mode

Lists the different modes of opening the file, which is open()the second parameter. The parameter with b means operation binary file, and operation text file without b.
Excerpt from Python file reading and writing (open (), close (), with open () as f ...

mode description
r Open the file as read-only. The file pointer will be placed at the beginning of the file. This is the default mode.
rb Open a file in binary format for read-only. The file pointer will be placed at the beginning of the file. This is the default mode.
r+ Open a file for reading and writing. The file pointer will be placed at the beginning of the file.
rb+ Open a file in binary format for reading and writing. The file pointer will be placed at the beginning of the file.
w Open a file for writing only. If the file already exists, it will be overwritten. If the file does not exist, create a new file.
wb Open a file in binary format for writing only. If the file already exists, it will be overwritten. If the file does not exist, create a new file.
w+ Open a file for reading and writing. If the file already exists, it will be overwritten. If the file does not exist, create a new file.
wb+ Open a file in binary format for reading and writing. If the file already exists, it will be overwritten. If the file does not exist, create a new file.
a Open a file for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written after the existing content. If the file does not exist, create a new file for writing.
from Open a file for appending in binary format. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written after the existing content. If the file does not exist, create a new file for writing.
a+ Open a file for reading and writing. If the file already exists, the file pointer will be placed at the end of the file. The file will be in append mode when it is opened. If the file does not exist, create a new file for reading and writing.
from + Open a file for appending in binary format. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, create a new file for reading and writing.

Guess you like

Origin www.cnblogs.com/charleechan/p/12698637.html