Tabs python difference in the r and rb

 

A, Python file read and write modes:

r, rb, w, wb then when reading and writing files, whether the main difference b identified where is it?

 

1, file usage logo

'r': Default, indicates the data read from the file.
'w': To indicates data file write, and truncate the previous contents
'a': indicates the file To write data to the current content tail
'r +': indicates the file read-write operations (delete the previous All data)
'R & lt + A': indicates the file can be read and written (added to the current end of the file)
'B': reading and writing binary data to be represented

 

2, read file read file operations, read the documents until the terminator (EOF) is considered to read the final document, Python would think byte \ x1A (26) is converted into a character for the document terminator (EOF),

      Therefore, when using the 'r' for reading a binary file, reads the document may appear incomplete phenomenon.

 

Example:
     Binary file there is arranged in the high-low data: 7F 32 1A 2F 3D 2C 12 2E 76
     if 'r' is read, then read the third byte, i.e. that end of the file.
     If 'rb' read in binary bits, the read byte is not converted into characters, thereby avoiding the above error.


Solution:
     binary file binary method to read 'rb'

  Summary:
     'r' is the time, if you encounter '0x1A', then regarded as the end of the file is EOF. Using 'rb' this problem does not exist,


That is: If you write and then read binary file, if one exists '0x1A', it will only read part of the file,
using the 'rb' will always read the end of the file.


3, the file for writing string x = 'abc \ ndef', we can use len (x) is obtained its length 7, \ n newline we call actually 0x0A. When we use the 'w' that is written in text mode when the windows platform will automatically '0x0A' into two characters '0x0D', '0x0A', ie the length of the document actually becomes 8. When reading 'r' text, and automatically converted to the original line breaks. If you replace 'wb' binary way to write it, a character will remain unchanged, as it is read when reading. So if write, read text with binary way, then I would consider this extra byte of. '0x0D', also known as a carriage return. Will not change under Linux, because only linux '0X0A' for newline.

Guess you like

Origin www.cnblogs.com/laogao123/p/11071890.html