Python file IO 'w' vs 'wb'

19,374

Only in Windows, in the latter case, .write('\n') writes one byte with a value of 10. In the former case, it writes two bytes, with the values 13 and 10.

You can prove this to yourself by looking at the resulting file size, and examining the files in a hex editor.

In POSIX-related operating systems (UNIX, SunOS, MacOS, Linux, etc.), there is no difference beetween 'w' and 'wb'.

Share:
19,374
pj2452
Author by

pj2452

Updated on June 08, 2022

Comments

  • pj2452
    pj2452 almost 2 years

    Wondering what the real difference is when writing files from Python. From what I can see if I use w or wb I am getting the same result with text.

    I thought that saving as a binary file would show only binary values in a hex editor, but it also shows text and then ASCII version of that text.

    Can both be used interchangably when saving text? (Windows User)

    • Mark Ransom
      Mark Ransom about 11 years
      No, you're not getting the same result. Open the file in a binary editor and look at the line endings.
    • pj2452
      pj2452 about 11 years
      Okay, I noticed that when using 'w' there is an added '\r' (carriage return) present with a newline, but when using 'wb' there is no '\r'. Odd...
    • matth
      matth about 11 years
      @pj2452 - Not odd. That is the definition of (and the original intnet of) using 'b'.