My friends, for reprint please indicate the source: blog.csdn.net/jiangjunsho…

Disclaimer: During the teaching of artificial intelligence technology, many students asked me some python related questions, so in order to let students master more extended knowledge and better understand AI technology, I asked my assistant to share this Python series of tutorials, hoping to help you! Since this Python tutorial is not written by me, it is not as funny and boring as my AI teaching. But its knowledge points or say in place, also worth reading! PS: if you don’t understand this article, please read the previous article first. Step by step, you won’t feel difficult to learn a little every day!

In Both Python 3.0 and Python 2.6, the file type is determined by the second argument to open, which can be called a pattern string. If the string contains a “B”, the file is opened in binary form, otherwise it is opened as text.

Python has always supported text and binary files, but in Python 3.0 there are clear differences between the two: • Text files represent content as regular STR strings, perform Unicode encoding and decoding automatically, and perform last-line conversions by default. • A binary file represents the content as a special bytes string type and allows programs to access the file content unmodified.

If you need to work with internationalized applications or byte-oriented data, the differences in Python 3.0 affect your code. In general, you must use bytes strings for binary files and regular STR strings for text files. Also, because text files implement Unicode encoding, you cannot open a binary data file in text mode — otherwise decoding its contents into Unicode text may fail.

Let’s look at an example. When you read a binary data file, you get a bytes object:

>>> data = open ('data.bin','rb').read () # open binary file: rb=read binary >>> data # bytes string holds binary data b'\x00\x00\x00\x07spam\x00\x08' >>> data[4:8] # Act like Strings b'spam' >>> data[0] # But really are small 8-bit integers 115 >>> bin (data[0]) # Python 3.0 bin () function '0b1110011'Copy the code

In addition, binaries do not perform any last-line conversions to the data. So when you read and write files, you need to know whether you’re reading or writing files in binary form. A file written as text must also be read as text. A file written in binary must be read in binary!