Differences between opening files in binary and text formats

Source: Internet
Author: User

Binary File processing problems

When processing binary files, use the following method:

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

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.

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.