Python series of tutorials 122

Friends, if you need to 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 the students have more extended knowledge and a better understanding of AI technology, I asked my assistant to share this series of python tutorials. I hope Can help everyone! Since this python tutorial is not written by me, it is not as funny and humorous as my AI technology teaching, and it is more boring to learn; but its knowledge points are still in place, and it is also worth reading! PS: For students who do not understand this article, please read the previous article first, and you will not find it difficult to learn a little bit every day step by step!

In Python 3.0 and Python 2.6, the file type is determined by the second parameter of open, which can be called a pattern string. If the string contains a "b", it means that the file is opened in binary form, otherwise it is in text form.

Python has always supported text and binary files, but in Python 3.0, there is a clear distinction between the two: • Text files represent their content as regular str strings, perform automatic Unicode encoding and decoding, and execute last line by default convert. • Binary files represent the content as a special type of bytes string, and allow programs to access the file content without modification.

Differences in Python 3.0 affect code if you need to deal with internationalized applications or byte-oriented data. Typically, you have to use bytes strings for binary files, and regular str strings for text files. Also, since text files implement Unicode encoding, a binary data file cannot be opened in text mode - otherwise decoding its contents to 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'
复制代码

Also, the binary file does not perform any end-of-line conversion on the data. Therefore, when reading and writing files, it is necessary to distinguish whether to use text form or binary form. A file written in text form is also read in text form. A file written in binary form must be read in binary form!

Guess you like

Origin juejin.im/post/7025499800007081991