A simple method for reading and writing binary files using Python

Source: Internet
Author: User
The following is a simple method for reading and writing binary files using Python (recommended ). I think this is quite good. now I will share it with you and give you a reference. Let's take a look at the general feeling: python itself does not support binary, but it provides a module to make up for, that is, the struct module.

Python does not have binary data, but it can store binary data. it uses string to store binary data. This does not matter because string is in 1 byte.

Import struct

A = 12.34

# Convert a to binary

Bytes = struct. pack ('I',)

In this case, bytes is a string, and the bytes of the string are the same as the binary storage content of.

Then perform a reverse operation.

The existing binary data bytes (actually a string) is converted to the python data type in turn:

A, = struct. unpack ('I', bytes)

Note that the unpack returns tuple

So if there is only one variable:

Bytes = struct. pack ('I',)

This is required for decoding.

A, = struct. unpack ('I', bytes) or (a,) = struct. unpack ('I', bytes)

If a = struct. unpack ('I', bytes) is used directly, a = (12.34,) is a tuple instead of the original floating point number.

If it is composed of multiple data, you can do this:

a='hello'b='world!'c=2d=45.123bytes=struct.pack('5s6sif',a,b,c,d)

In this case, bytes is binary data. you can directly write data to a file, such as binfile. write (bytes)

Then, we can read it again when needed, bytes = binfile. read ()

Then, the python variable is decoded by struct. unpack ().

A, B, c, d = struct. unpack ('5s6sif', bytes)

'5s6sif' is called fmt. it is a formatted string consisting of numbers and characters. 5s indicates the five-character string, 2i indicates two integers, and so on, the following are available characters and types. the ctype can correspond to the types in python.


Format C Type Python Bytes
X Pad byte No value 1
C Char String of length 1 1
B Signed char Integer 1
B Unsigned char Integer 1
? _ Bool Bool 1
H Short Integer 2
H Unsigned short Integer 2
I Int Integer 4
I Unsigned int Integer or long 4
L Long Integer 4
L Unsigned long Long 4
Q Long Long 8
Q Unsigned long Long 8
F Float Float 4
D Double Float 8
S Char [] String 1
P Char [] String 1
P Void * Long

The last one can be used to indicate the pointer type, which occupies 4 bytes.

In order to exchange data with the struct in c, some c or c ++ compilers use byte alignment, which is usually a 32-bit system with 4 bytes.

Character Byte order Size and alignment
@ Native Native makes up 4 bytes
= Native Standard is based on the number of original bytes
< Little-endian Standard is based on the number of original bytes
> Big-endian Standard is based on the number of original bytes
! Network (= big-endian) Standard is based on the number of original bytes

The usage is placed at the first position of fmt, like '@ 5s6sif'

----- Problems encountered during binary file processing -----

When processing binary files, use the following method:

Binfile = open (filepath, 'RB') read binary files

Or

Binfile = open (filepath, 'WB ') to write binary files

So what is the difference between the result of binfile = open (filepath, 'r?

There are two differences:

First, if you encounter '0x1a 'when using 'R', it is regarded as the end of the file, which is EOF. This problem does not exist when 'RB' is used. That is, if you use binary data to write and then read the data in text, if '0x1a 'exists, only part of the file will be read. When 'RB' is used, it will always read at the end of the file.

Second, for string x = 'ABC/ndef ', we can use len (x) to get its length of 7./n is called a line break, which is actually '0x0a '. When we use 'w' as the text writing method, '0x0a' is automatically changed to two characters '0x0d' and '0x0a' on windows ', that is, the file length is actually 8 .. When reading in 'r' text, it is automatically converted to the original line break. If it is written in 'WB 'binary format, it will keep one character unchanged and read as is. Therefore, if you write data in text and read data in binary mode, consider the extra byte. '0x0d' is also called a carriage return.
Linux does not change. Because linux only uses '0x0a' to indicate line breaks.

The above simple method for reading and writing binary files using Python (recommended) is all the content shared by Alibaba Cloud Xiaobian. I hope to give you a reference and support for PHP.

For more information about how to use Python to read and write binary files, see PHP!

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.