\r\n or \n notepad editor end line ???

Steven D'Aprano steve at REMOVETHIScyber.com.au
Mon Jun 13 19:23:07 EDT 2005


On Mon, 13 Jun 2005 10:52:52 -0400, Peter Hansen wrote:

> Steven D'Aprano wrote:
>> When you read a Windows text file using "r" mode, what happens to the \r
>> immediately before the newline? Do you have to handle it yourself? Or will
>> Python cleverly suppress it so you don't have to worry about it?
>> 
>> And when you write a text file under Python using "w" mode, will the
>> people who come along afterwards to edit the file in Notepad curse your
>> name? Notepad expects \r\n EOL characters, and gets cranky if the \r is
>> missing.
> 
> This is Python.  Fire up the interactive interpreter and try it out!  It 
> will take all of two or three minutes...

Which I would have done, except see comment below:

>> How does this behaviour differ from "universal newlines"?
> 
> If you open a text file created with a different line-ending convention 
> than that used on your own platform, you may get "interesting" results. 

I'm using Linux, not Windows. Of course I *could* try to fake reading and
writing Windows files from Linux, but that would require me actually
understanding how Python deals with line endings across the platforms in
order to generate them in the first place. But if I understood it, I
wouldn't have needed to ask the question.

And I would still be none the wiser about Python's behaviour when running
under Windows -- that's hard to fake on a Linux box.

>   If you use "rU" instead, you will receive only \n line endings and not
> have anything to worry about.  (For example, reading a Windows text file
> on Linux will give you lines that have \r\n endings in them... not what
> you really want.  Using "rU" will give you just \n line endings whether
> you are on Linux or Windows.)

So going back to the original question... if I open in "r" mode a text
file which was created under Windows, I will get \r characters in the
text and have to deal with them regardless of what platform I am running
Python under. Correct?

If I use "rU" mode Python suppress the \r characters. When I write a
string back, I'm responsible for making sure the EOL markers are correct
for whatever platform I expect the file to be read under. Unless Python
can somehow magically read my mind and know that even though I'm writing
the file under Linux it will be read later under Windows. Am I close?


(Ew, I hate cross-platform issues. They make my head hurt.)


-- 
Steve.




More information about the Python-list mailing list