7

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)

Remi Guan
  • 21,506
  • 17
  • 64
  • 87
pj2452
  • 905
  • 3
  • 10
  • 22
  • No, you're not getting the same result. Open the file in a binary editor and look at the line endings. – Mark Ransom Apr 01 '13 at 20:01
  • 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... – pj2452 Apr 01 '13 at 20:15
  • @pj2452 - Not odd. That is the definition of (and the original intnet of) using `'b'`. – Robᵩ Apr 01 '13 at 20:48

1 Answers1

9

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'.

Robᵩ
  • 163,533
  • 20
  • 239
  • 308