Writing binary files in windows

Nick Raptis airscorp at otenet.gr
Fri Feb 11 22:38:02 EST 2011


On 02/12/2011 05:20 AM, Abhishek Gulyani wrote:
> When I write binary files in windows:
>
> file  = open(r'D:\Data.bin','wb')
> file.write('Random text')
> file.close()
>
> and then open the file it just shows up as normal text. There is 
> nothing binary about it. Why is that?
>
> Sorry if this is too much of a noobie question. I tried googling 
> around but couldn't find an answer.
>
But then, you opened the file you created in Notepad and saw that the 
lines weren't wrapping maybe?

It all comes down to Line endings. Read here to see what LF vs. CRLF is 
all about http://en.wikipedia.org/wiki/Newline#Representations

You see, when you read a file, Python converts both LF and CRLF to "\n". 
When you write a "\n" to a file Python writes CRLF in Windows and just 
LF in Unix machines.
That'd be a heck troublesome when dealing with binary files, hence the 
'b' flag. It basically means *Don't convert newlines", and it's pretty 
common in software.

So, to answer your question: If you're only writing text to a file, 
you'll only see a difference if your external text editor isn't smart 
enough to treat both LF and CRLF as newlines. Like Notepad did back in 
the day, and maybe still does.
But if you're writing binary stuff, it makes all the difference in the 
world.

Nick



More information about the Python-list mailing list